28
A Tiny URL design and code βοΈ
This is a simple
encode()
and decode()
function.Note that we haven't created the MD5 hashing approach here as this only deals with the concept.
encode(id)
functionprivate static final String allowedString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private final char[] allowedCharacters = allowedString.toCharArray();
private final int base = allowedCharacters.length; // 62
public String encode(long input){
var encodedString = new StringBuilder();
if(input == 0) {
return String.valueOf(allowedCharacters[0]);
}
while (input > 0) {
encodedString.append(allowedCharacters[(int) (input % base)]);
input = input / base;
}
return encodedString.reverse().toString();
}
62^remaining characters
public long decode(String input) {
var characters = input.toCharArray();
var length = characters.length;
var decoded = 0;
//counter is used to avoid reversing input string
var counter = 1;
for (char character : characters) {
decoded += allowedString.indexOf(character) * Math.pow(base, length - counter);
counter++;
}
return decoded;
}
So if we have the decoded url, we could simply return it as a header location - with the response code of
302 (FOUND)
@GetMapping(value = "{shortUrl}")
public ResponseEntity<Void> getAndRedirect(@PathVariable String shortUrl) {
var url = urlService.getOriginalUrl(shortUrl);
return ResponseEntity.status(HttpStatus.FOUND)
.location(URI.create(url))
.build();
}
}
I will be working on a more distributed solutions in coming posts, Thanks you for reaching here.
Here's a πͺ
Here's a πͺ
28