Http Server in Logo
Here’s the translation of the HTTP Server example from Go to Java, formatted in Markdown suitable for Hugo:
Our first 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 HTTPServer {
public static void main(String[] args) throws IOException {
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();
for (String key : t.getRequestHeaders().keySet()) {
response.append(key).append(": ")
.append(String.join(", ", t.getRequestHeaders().get(key)))
.append("\n");
}
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.toString().getBytes());
os.close();
}
}
}
In Java, we use the HttpHandler
interface to define our request handlers. This is similar to the concept of handlers in the net/http
package.
The HelloHandler
and HeadersHandler
classes implement the HttpHandler
interface, providing the logic for handling requests to the /hello
and /headers
endpoints respectively.
In the main
method, we create an HttpServer
instance, set up the context paths with their corresponding handlers, and start the server.
To run the server:
$ javac HTTPServer.java
$ java HTTPServer &
Now you can access the /hello
route:
$ curl localhost:8090/hello
hello
This example demonstrates how to set up a basic HTTP server in Java, register handlers for different routes, and process incoming requests. The structure is similar to the original example, but uses Java-specific classes and interfaces to achieve the same functionality.