Http Server in Groovy

Here’s the translation of the HTTP Server example from Go to Groovy, formatted in Markdown suitable for Hugo:

Creating a basic HTTP server in Groovy is straightforward using the 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

// A fundamental concept in HTTP servers is handlers. A handler is an object 
// implementing the HttpHandler interface. In Groovy, we can use closures 
// to create handlers easily.

def hello = { HttpExchange exchange ->
    // Handlers take a HttpExchange object as an argument. This object is used 
    // to handle the request and send the response. Here our simple response 
    // is just "hello\n".
    exchange.responseHeaders.set("Content-Type", "text/plain")
    exchange.sendResponseHeaders(200, 0)
    exchange.responseBody.withWriter { writer ->
        writer.write("hello\n")
    }
    exchange.close()
} as HttpHandler

def headers = { HttpExchange exchange ->
    // This handler does something a little more sophisticated by reading all 
    // the HTTP request headers and echoing them into the response body.
    exchange.responseHeaders.set("Content-Type", "text/plain")
    exchange.sendResponseHeaders(200, 0)
    exchange.responseBody.withWriter { writer ->
        exchange.requestHeaders.each { name, values ->
            values.each { value ->
                writer.write("${name}: ${value}\n")
            }
        }
    }
    exchange.close()
} as HttpHandler

// Create a new HTTP server that listens on port 8090
def server = HttpServer.create(new InetSocketAddress(8090), 0)

// We register our handlers on server routes using the createContext method
server.createContext("/hello", hello)
server.createContext("/headers", headers)

// Start the server
server.start()

println("Server started on port 8090")

To run the server:

$ groovy http-server.groovy
Server started on port 8090

You can then access the /hello route:

$ curl localhost:8090/hello
hello

This example demonstrates how to create a simple HTTP server in Groovy. It sets up two routes: /hello which responds with a simple greeting, and /headers which echoes back all the request headers.

The HttpServer class is used to create the server, and HttpHandler implementations (created using Groovy closures) are used to define the behavior for each route. The server is then started and listens for incoming requests.

While the API is different from Go’s net/http package, the concepts are similar. Both allow you to easily set up routes and define handlers for those routes.