Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A simple web server written in Groovy that provides static and code-generated content
#!/usr/bin/env groovy
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.servlet.*
import groovy.servlet.*
@Grab(group='org.eclipse.jetty.aggregate', module='jetty-all', version='7.6.15.v20140411')
def startJetty() {
def server = new Server(8080)
def handler = new ServletContextHandler(ServletContextHandler.SESSIONS)
handler.contextPath = '/'
handler.resourceBase = '.'
handler.welcomeFiles = ['index.html']
handler.addServlet(GroovyServlet, '/scripts/*')
def filesHolder = handler.addServlet(DefaultServlet, '/')
filesHolder.setInitParameter('resourceBase', './public')
server.handler = handler
println "Starting Jetty, press Ctrl+C to stop."

This comment has been minimized.

Copy link

@bitsnaps bitsnaps commented Mar 20, 2019

Even shorter with no dependencies:

int PORT = 8080
HttpServer.create(new InetSocketAddress(PORT), /*max backlog*/ 0).with {
    println "Server is listening on ${PORT}, hit Ctrl+C to exit."    
    createContext("/") { http ->
        http.responseHeaders.add("Content-type", "text/plain")
        http.sendResponseHeaders(200, 0)
        http.responseBody.withWriter { out ->
            out << "Hello ${http.remoteAddress.hostName}!\n"
        println "Hit from Host: ${http.remoteAddress.hostName} on port: ${http.remoteAddress.holder.port}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment