Last active
January 6, 2025 20:04
-
-
Save qubyte/8513745 to your computer and use it in GitHub Desktop.
Super simple URL unshortener in Dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:io' show HttpRequest, HttpClient, HttpServer, ContentType; | |
import 'dart:convert' show JSON; | |
void handleRequest(HttpRequest request) { | |
// For convenience. | |
var response = request.response; | |
// No path is expected. Return with 404 for anything else. | |
if (request.uri.path != '' && request.uri.path != '/') { | |
response.statusCode = 404; | |
response.close(); | |
return; | |
} | |
var query = request.uri.queryParameters; | |
// If there was no url query parameter, return with 400. | |
if (query['url'] == null) { | |
response.statusCode = 400; | |
response.close(); | |
return; | |
} | |
var url = Uri.parse(query['url']); | |
// We have the information needed to make a request to a remote server. Create a client. | |
var client = new HttpClient(); | |
// Make a HEAD request to resolve redirects, but avoid unnecessary data. | |
client.openUrl('HEAD', url) | |
.then((req) => req.close()) | |
.then((res) { | |
// The response will be JSON. | |
response.headers.contentType = ContentType.parse('application/json; charset=utf-8'); | |
// Encode a JSON object with the original and resolved URLs and write it to the response. | |
response.write(JSON.encode({ | |
'original': query['url'], | |
'resolved': res.redirects.last.location.toString() | |
})); | |
response.close(); | |
}); | |
} | |
void main() { | |
HttpServer.bind('127.0.0.1', 8080) | |
.then((server) { | |
print('Server listening...'); | |
server.listen(handleRequest); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated to use
show
. Definitely much nicer.