Skip to content

Instantly share code, notes, and snippets.

@renatoathaydes
Last active October 23, 2023 15:28
Show Gist options
  • Save renatoathaydes/8ad276cedd515f8ff5fc to your computer and use it in GitHub Desktop.
Save renatoathaydes/8ad276cedd515f8ff5fc to your computer and use it in GitHub Desktop.
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
server.start()
}
println "Starting Jetty, press Ctrl+C to stop."
startJetty()
@bitsnaps
Copy link

bitsnaps commented Mar 20, 2019

Even shorter with no dependencies:

import com.sun.net.httpserver.HttpServer
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}"
    }
    start()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment