restful-serve-static.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "path"
  6. "github.com/emicklei/go-restful"
  7. )
  8. // This example shows how to define methods that serve static files
  9. // It uses the standard http.ServeFile method
  10. //
  11. // GET http://localhost:8080/static/test.xml
  12. // GET http://localhost:8080/static/
  13. //
  14. // GET http://localhost:8080/static?resource=subdir/test.xml
  15. var rootdir = "/tmp"
  16. func main() {
  17. restful.DefaultContainer.Router(restful.CurlyRouter{})
  18. ws := new(restful.WebService)
  19. ws.Route(ws.GET("/static/{subpath:*}").To(staticFromPathParam))
  20. ws.Route(ws.GET("/static").To(staticFromQueryParam))
  21. restful.Add(ws)
  22. println("[go-restful] serving files on http://localhost:8080/static from local /tmp")
  23. http.ListenAndServe(":8080", nil)
  24. }
  25. func staticFromPathParam(req *restful.Request, resp *restful.Response) {
  26. actual := path.Join(rootdir, req.PathParameter("subpath"))
  27. fmt.Printf("serving %s ... (from %s)\n", actual, req.PathParameter("subpath"))
  28. http.ServeFile(
  29. resp.ResponseWriter,
  30. req.Request,
  31. actual)
  32. }
  33. func staticFromQueryParam(req *restful.Request, resp *restful.Response) {
  34. http.ServeFile(
  35. resp.ResponseWriter,
  36. req.Request,
  37. path.Join(rootdir, req.QueryParameter("resource")))
  38. }