Http Server in Fortress
Here’s the translation of the HTTP server example from Go to Java, formatted in Markdown suitable for Hugo:
Our HTTP server example demonstrates how to create a basic server using Java’s built-in com.sun.net.httpserver
package.
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
public class HttpServerExample {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8090), 0);
server.createContext("/hello", new HelloHandler());
server.createContext("/headers", new HeadersHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class HelloHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = "hello\n";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
static class HeadersHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
StringBuilder response = new StringBuilder();
t.getRequestHeaders().forEach((key, values) -> {
values.forEach(value -> response.append(key).append(": ").append(value).append("\n"));
});
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.toString().getBytes());
os.close();
}
}
}
In Java, we use the HttpServer
class from the com.sun.net.httpserver
package to create a basic HTTP server. The concept of handlers in Java is similar, implemented through the HttpHandler
interface.
We define two handler classes: HelloHandler
and HeadersHandler
. These classes implement the HttpHandler
interface and override the handle
method to process incoming requests.
The HelloHandler
simply responds with “hello\n”, while the HeadersHandler
reads all the HTTP request headers and echoes them in the response body.
In the main
method, we create the server, set up the routes using createContext
, and start the server.
To run the server:
$ javac HttpServerExample.java
$ java HttpServerExample &
You can then access the /hello
route:
$ curl localhost:8090/hello
hello
This example demonstrates how to set up a basic HTTP server in Java, define custom request handlers, and process incoming HTTP requests.