Title here
Summary here
import 'dart:io';
// A fundamental concept in HTTP servers is handlers. In Dart, we can use
// functions with the appropriate signature as handlers.
void hello(HttpRequest request) {
// Functions serving as handlers take an HttpRequest as an argument.
// We can use the response property to fill in the HTTP response.
// Here our simple response is just "hello\n".
request.response.write('hello\n');
request.response.close();
}
void headers(HttpRequest request) {
// This handler does something a little more sophisticated by reading
// all the HTTP request headers and echoing them into the response body.
request.headers.forEach((name, values) {
for (var v in values) {
request.response.write('$name: $v\n');
}
});
request.response.close();
}
void main() async {
// We create a HttpServer and listen on a port.
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 8090);
print('Listening on localhost:${server.port}');
// We handle requests using a switch statement on the request's URI path.
await for (HttpRequest request in server) {
switch (request.uri.path) {
case '/hello':
hello(request);
break;
case '/headers':
headers(request);
break;
default:
request.response.statusCode = HttpStatus.notFound;
request.response.close();
}
}
}
To run the server:
http_server.dart
.$ dart run http_server.dart
Listening on localhost:8090
You can then access the server using curl:
$ curl localhost:8090/hello
hello
$ curl localhost:8090/headers
host: localhost:8090
user-agent: curl/7.68.0
accept: */*
This Dart code creates a simple HTTP server that listens on port 8090 and handles two routes: /hello
and /headers
. The /hello
route responds with a simple “hello” message, while the /headers
route echoes back all the headers from the incoming request.
The main differences from the original example are:
dart:io
library for HTTP server functionality instead of net/http
.HttpServer
instance and use a stream to handle incoming requests, rather than registering handlers with a global function.HttpRequest
object combines both the request and response functionality, unlike Go’s separate http.ResponseWriter
and http.Request
.This example demonstrates how to create a basic HTTP server in Dart, handling different routes and working with request headers.