|
Groovy example source code file (SimpleWebServer.groovy)
The Groovy SimpleWebServer.groovy source code
/**
* Simple web server
* @author <a href="mailto:jeremy.rayner@gmail.com">Jeremy Rayner
*
* invoke using
* groovy -l 80 SimpleWebServer.groovy
*
* (where 80 is the port to listen for requests upon)
*/
import java.io.File
if (init) {
headers = [:]
binaryTypes = ["gif","jpg","png"]
mimeTypes = [
"css" : "text/css",
"gif" : "image/gif",
"htm" : "text/html",
"html": "text/html",
"jpg" : "image/jpeg",
"png" : "image/png"
]
}
// parse the request
if (line.toLowerCase().startsWith("get")) {
content = line.tokenize()[1]
} else {
h = line.tokenize(":")
headers[h[0]] = h[1]
}
// all done, now process request
if (line.size() == 0) {
processRequest()
return "success"
}
// ------------------------
def processRequest() {
if (content.indexOf("..") < 0) { //simplistic security
// simple file browser rooted from current dir
f = new File("." + content)
if (f.isDirectory()) {
printDirectoryListing(f)
} else {
extension = content.substring(content.lastIndexOf(".") + 1)
printHeaders(mimeTypes.get(extension,"text/plain"))
if (binaryTypes.contains(extension)) {
socket.outputStream.write(f.readBytes())
} else {
println(f.text)
}
}
}
}
def printDirectoryListing(f) {
printHeaders("text/html")
println "<html>"
for (i in f.list().toList().sort()) {
if ("/" == content) { content = "" } // special case for root document
println "<a href='${content}/${i}'>${i}
Other Groovy examples (source code examples)Here is a short list of links related to this Groovy SimpleWebServer.groovy source code file: |
| ... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.