webserv.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (C) 2015 Antoine Tenart
  3. *
  4. * Antoine Tenart <antoine.tenart@ack.tf>
  5. *
  6. * This file is licensed under the terms of the GNU General Public
  7. * License version 2. This program is licensed "as is" without any
  8. * warranty of any kind, whether express or implied.
  9. */
  10. package main
  11. import (
  12. "errors"
  13. "net/http"
  14. "os"
  15. "path"
  16. docopt "github.com/docopt/docopt-go"
  17. )
  18. var (
  19. version = "webserv 0.1"
  20. usage = `Temporary http server to serve files
  21. Usage:
  22. webserv [-d <directory> | -f <file>] [-p <port>]
  23. webserv --help
  24. Options:
  25. -d <directory>, --dir <directory> Serve the given directory [default: ./]
  26. -f <file>, --file <file> Serve the given file
  27. -p <port>, --port <port> Port number to listen on [default: 8080]
  28. --help Print this help
  29. `
  30. )
  31. type File string
  32. func (f File) Open(name string) (http.File, error) {
  33. if name != ("/" + path.Clean(string(f))) {
  34. return nil, errors.New("http: invalid request")
  35. }
  36. file, err := os.Open(string(f))
  37. if err != nil {
  38. return nil, err
  39. }
  40. return file, nil
  41. }
  42. func main() {
  43. var fs http.FileSystem
  44. args, _ := docopt.Parse(usage, os.Args[1:], true, version, true)
  45. if f, ok := args["--file"].(string); ok {
  46. fs = File(f)
  47. } else {
  48. fs = http.Dir(args["--dir"].(string))
  49. }
  50. http.Handle("/", http.FileServer(fs))
  51. http.ListenAndServe(":" + args["--port"].(string), nil)
  52. }