-
-
Save limcheekin/f4ccf92d52101d841efce564acb608d7 to your computer and use it in GitHub Desktop.
Minimal Groovy for a static webserver. Suitable for use with gradle run
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment