Skip to content

Instantly share code, notes, and snippets.

@iamnoah
Created March 6, 2014 16:33
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save iamnoah/9393655 to your computer and use it in GitHub Desktop.
Save iamnoah/9393655 to your computer and use it in GitHub Desktop.
Minimal Groovy for a static webserver. Suitable for use with gradle run
/**
* Usage:
groovy webServer.groovy [-Pport=80] [-PwebRoot=/path/to/files]
*
* Or with gradle, place in src/main/groovy, and place assets in src/main/webapp
* and use as the mainClassName.
*/
import com.sun.net.httpserver.*
// only supports basic web content types
final TYPES = [
"css": "text/css",
"gif": "image/gif",
"html": "text/html",
"jpg": "image/jpeg",
"js": "application/javascript",
"png": "image/png",
"svg": "image/svg+xml",
]
def port = System.properties.port?.toInteger() ?: 8680
def root = new File(System.properties.webroot ?: "src/main/webapp")
def server = HttpServer.create(new InetSocketAddress(port), 0)
server.createContext("/", { HttpExchange exchange ->
try {
if (!"GET".equalsIgnoreCase(exchange.requestMethod)) {
exchange.sendResponseHeaders(405, 0)
exchange.responseBody.close()
return
}
def path = exchange.requestURI.path
println "GET $path"
// path starts with /
def file = new File(root, path.substring(1))
if (file.isDirectory()) {
file = new File(file, "index.html")
}
if (file.exists()) {
exchange.responseHeaders.set("Content-Type",
TYPES[file.name.split(/\./)[-1]] ?: "text/plain")
exchange.sendResponseHeaders(200, 0)
file.withInputStream {
exchange.responseBody << it
}
exchange.responseBody.close()
} else {
exchange.sendResponseHeaders(404, 0)
exchange.responseBody.close()
}
} catch(e) {
e.printStackTrace()
}
} as HttpHandler)
server.start()
println "started simple web server on port ${port}"
@jagedn
Copy link

jagedn commented Dec 29, 2016

Thanks for the git but you need to correct some typos when execute from console

groovy -Dwebroot=./my-dir -Dport=8080 webServer.groovy

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