Skip to content

Instantly share code, notes, and snippets.

@hron84
Created December 3, 2014 14:59
Show Gist options
  • Save hron84/9ddd537550e933421ff5 to your computer and use it in GitHub Desktop.
Save hron84/9ddd537550e933421ff5 to your computer and use it in GitHub Desktop.
Duke server

DukeServer

This script is just provides a basic builder for the com.sun.net.httpserver.HttpServer and does some magic to make Groovy closures to work easily.

Pros:

  • This stuff has no dependency other than JRE >= 1.6 and Groovy runtime
  • Building a server is quick and painless.

Cons:

  • The Sun's default handler classs is quite basic. I plan to make a bit better handler wrapper class to be able respond to requests by HTTP verbs and provide more details about the request. It will be available later. Or not :-)
package me.hron.dukeserver
import java.util.concurrent.Executor
import com.sun.net.httpserver.*
public class ServerBuilder {
String address
int port
Executor executor
Map handlers = [:]
public static HttpServer buildServer(Closure closure) {
ServerBuilder builder = new ServerBuilder()
closure.delegate = builder
closure.call()
return builder.build()
}
public HttpServer build() {
if(address == null || address == "") {
address = "0.0.0.0"
}
if(port < 1024) {
port = 8000 + port
}
HttpServer server = HttpServer.create(new InetSocketAddress(address, port), 0)
if(executor != null) {
server.executor = executor
}
println "Server configuration is done, it will start at ${address}:${port}"
if(!handlers.isEmpty()) {
handlers.each { path, handler ->
if(handler == null) {
println "Mapping empty context to ${path}"
server.createContext(path)
} else if(handler instanceof HttpHandler) {
println "Mapping route to ${path}"
server.createContext(path, handler)
} else if(handler instanceof Closure) {
println "Mapping route to ${path}"
server.createContext(path, handler as HttpHandler)
}
}
}
return server
}
}
import me.hron.dukeserver.ServerBuilder
server = ServerBuilder.buildServer {
address = '0.0.0.0'
port = 80
handlers['/'] = { exchange ->
exchange.responseHeaders.set 'Content-Type', 'text/plain'
exchange.sendResponseHeaders 200, 12
exchange.responseBody << "Hello, world"
}
}
server.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment