PageRenderTime 91ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/src/examples/commandLineTools/SimpleWebServer.groovy

https://github.com/logicdisaster/groovy-core
Groovy | 74 lines | 53 code | 8 blank | 13 comment | 13 complexity | 1a1b32cd4d190c2b31e83eb08297f329 MD5 | raw file
  1. /**
  2. * Simple web server
  3. * @author <a href="mailto:jeremy.rayner@gmail.com">Jeremy Rayner</a>
  4. *
  5. * invoke using
  6. * groovy -l 80 SimpleWebServer.groovy
  7. *
  8. * (where 80 is the port to listen for requests upon)
  9. */
  10. import java.io.File
  11. if (init) {
  12. headers = [:]
  13. binaryTypes = ["gif","jpg","png"]
  14. mimeTypes = [
  15. "css" : "text/css",
  16. "gif" : "image/gif",
  17. "htm" : "text/html",
  18. "html": "text/html",
  19. "jpg" : "image/jpeg",
  20. "png" : "image/png"
  21. ]
  22. }
  23. // parse the request
  24. if (line.toLowerCase().startsWith("get")) {
  25. content = line.tokenize()[1]
  26. } else {
  27. h = line.tokenize(":")
  28. headers[h[0]] = h[1]
  29. }
  30. // all done, now process request
  31. if (line.size() == 0) {
  32. processRequest()
  33. return "success"
  34. }
  35. // ------------------------
  36. def processRequest() {
  37. if (content.indexOf("..") < 0) { //simplistic security
  38. // simple file browser rooted from current dir
  39. f = new File("." + content)
  40. if (f.isDirectory()) {
  41. printDirectoryListing(f)
  42. } else {
  43. extension = content.substring(content.lastIndexOf(".") + 1)
  44. printHeaders(mimeTypes.get(extension,"text/plain"))
  45. if (binaryTypes.contains(extension)) {
  46. socket.outputStream.write(f.readBytes())
  47. } else {
  48. println(f.text)
  49. }
  50. }
  51. }
  52. }
  53. def printDirectoryListing(f) {
  54. printHeaders("text/html")
  55. println "<html><head></head><body>"
  56. for (i in f.list().toList().sort()) {
  57. if ("/" == content) { content = "" } // special case for root document
  58. println "<a href='${content}/${i}'>${i}</a><br>"
  59. }
  60. println "</body></html>"
  61. }
  62. def printHeaders(mimeType) {
  63. println "HTTP/1.0 200 OK"
  64. println "Content-Type: ${mimeType}"
  65. println ""
  66. }