Skip to content

Instantly share code, notes, and snippets.

@wololock
Created March 19, 2019 16:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wololock/eab9ec164f90816484ca7145b55759ab to your computer and use it in GitHub Desktop.
Save wololock/eab9ec164f90816484ca7145b55759ab to your computer and use it in GitHub Desktop.
import com.sun.net.httpserver.HttpExchange
import com.sun.net.httpserver.HttpHandler
import com.sun.net.httpserver.HttpServer
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
@CompileStatic
@TypeChecked
class GroovyHttpServer {
static void main(String[] args) {
def port = args.length > 0 ? args[0].toInteger() : 8080
def baseDir = args.length > 1 ? new File(args[1]).canonicalFile : new File(".").canonicalFile
def server = HttpServer.create(new InetSocketAddress(port), 0)
server.createContext("/", new HttpHandler() {
@Override
void handle(HttpExchange exchange) throws IOException {
def uri = exchange.requestURI
def file = new File(baseDir, uri.path).canonicalFile
if (!file.path.startsWith(baseDir.path)) {
sendResponse(exchange, 403, "403 (Forbidden)\n")
} else if (file.directory) {
String base = file == baseDir ? '': uri.path
String listing = linkify(base, file.list()).join("\n")
sendResponse(exchange, 200, "<html><body>${listing}</body></html>")
} else if (!file.file) {
sendResponse(exchange, 404, "404 (Not Found)\n")
} else {
sendResponse(exchange, 200, new FileInputStream(file))
}
}
})
server.executor = null
server.start()
println "Listening at http://localhost:${port}/"
}
static void sendResponse(HttpExchange ex, int code, InputStream ins) {
ex.sendResponseHeaders(code, 0)
ex.responseBody << ins
ex.responseBody.flush()
ex.responseBody.close()
}
static void sendResponse(HttpExchange ex, int code, byte[] answer) {
ex.sendResponseHeaders(code, answer.length)
ex.responseBody.write(answer)
ex.responseBody.close()
}
static void sendResponse(HttpExchange ex, int code, String answer) {
sendResponse(ex, code, answer.bytes)
}
static List<String> linkify(String base, String[] files) {
files.collect { file -> "<ul><a href=\"${base}/${file}\">${file}</a></ul>".toString() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment