Skip to content

Instantly share code, notes, and snippets.

@qubyte
Last active October 3, 2018 13:34
Show Gist options
  • Save qubyte/8513745 to your computer and use it in GitHub Desktop.
Save qubyte/8513745 to your computer and use it in GitHub Desktop.
Super simple URL unshortener in Dart
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);
});
}
@qubyte
Copy link
Author

qubyte commented Jan 20, 2014

The choice to import like this comes from my background with Node. I like keeping modules namespaced. Your show recommendation is nice though. That's a little like doing

var EventEmitter = require('events').EventEmitter; // Only needed EventEmitter.

so I may go that way. I figured that core was free when importing it explicitly like this broke prints, but stuck with it because I'm forced to think about what modules particular things come from as I use them.

@qubyte
Copy link
Author

qubyte commented Jan 20, 2014

Updated to use show. Definitely much nicer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment