Context in Groovy

Here’s the translation of the Go code to Groovy, along with explanations in Markdown format suitable for Hugo:

In the previous example we looked at setting up a simple HTTP server. HTTP servers are useful for demonstrating the usage of context management for controlling cancellation. In Groovy, we can use the Timer class and a custom TimerTask to simulate similar behavior.

import groovy.servlet.AbstractHttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.ServletContextHandler
import org.eclipse.jetty.servlet.ServletHolder

class HelloServlet extends AbstractHttpServlet {
    void doGet(HttpServletRequest request, HttpServletResponse response) {
        println "server: hello handler started"

        Timer timer = new Timer()
        TimerTask task = new TimerTask() {
            void run() {
                response.writer.println("hello")
                response.writer.flush()
                println "server: hello handler ended"
            }
        }

        timer.schedule(task, 10000)  // 10 seconds delay

        // Simulate cancellation after 5 seconds
        Thread.start {
            Thread.sleep(5000)
            timer.cancel()
            println "server: task canceled"
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Task canceled")
        }
    }
}

def server = new Server(8090)
def context = new ServletContextHandler(ServletContextHandler.SESSIONS)
context.contextPath = "/"
server.handler = context

context.addServlet(new ServletHolder(new HelloServlet()), "/hello")

server.start()
server.join()

In this Groovy example, we’re using the Jetty server to set up a simple HTTP server. The HelloServlet class handles requests to the “/hello” endpoint.

When a request is received, we create a Timer and a TimerTask that will respond after a 10-second delay. This simulates some work the server is doing.

To demonstrate cancellation, we start a separate thread that waits for 5 seconds and then cancels the timer. This simulates the cancellation of the task before it completes.

The Timer and TimerTask in this example serve a similar purpose to the context.Context in the original example, allowing us to cancel long-running operations.

To run the server:

$ groovy context.groovy &

Simulate a client request to /hello, and you’ll see the cancellation occur after 5 seconds:

$ curl localhost:8090/hello
server: hello handler started
server: task canceled

This example demonstrates how to manage long-running tasks and handle cancellation in a Groovy HTTP server context. While it doesn’t use the exact same mechanisms as the original example, it achieves a similar result in terms of functionality and behavior.