web.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Copyright 2014 Unknwon
  2. // Copyright 2014 Torkel Ödegaard
  3. package cmd
  4. import (
  5. "fmt"
  6. "net/http"
  7. "path"
  8. "github.com/Unknwon/macaron"
  9. "github.com/grafana/grafana/pkg/api"
  10. "github.com/grafana/grafana/pkg/api/static"
  11. "github.com/grafana/grafana/pkg/log"
  12. "github.com/grafana/grafana/pkg/middleware"
  13. "github.com/grafana/grafana/pkg/setting"
  14. )
  15. func newMacaron() *macaron.Macaron {
  16. macaron.Env = setting.Env
  17. m := macaron.New()
  18. m.Use(middleware.Logger())
  19. m.Use(macaron.Recovery())
  20. if setting.EnableGzip {
  21. m.Use(middleware.Gziper())
  22. }
  23. mapStatic(m, "", "public")
  24. mapStatic(m, "app", "app")
  25. mapStatic(m, "css", "css")
  26. mapStatic(m, "img", "img")
  27. mapStatic(m, "fonts", "fonts")
  28. mapStatic(m, "robots.txt", "robots.txxt")
  29. m.Use(macaron.Renderer(macaron.RenderOptions{
  30. Directory: path.Join(setting.StaticRootPath, "views"),
  31. IndentJSON: macaron.Env != macaron.PROD,
  32. Delims: macaron.Delims{Left: "[[", Right: "]]"},
  33. }))
  34. if setting.EnforceDomain {
  35. m.Use(middleware.ValidateHostHeader(setting.Domain))
  36. }
  37. m.Use(middleware.GetContextHandler())
  38. m.Use(middleware.Sessioner(&setting.SessionOptions))
  39. return m
  40. }
  41. func mapStatic(m *macaron.Macaron, dir string, prefix string) {
  42. headers := func(c *macaron.Context) {
  43. c.Resp.Header().Set("Cache-Control", "public, max-age=3600")
  44. }
  45. if setting.Env == setting.DEV {
  46. headers = func(c *macaron.Context) {
  47. c.Resp.Header().Set("Cache-Control", "max-age=0, must-revalidate, no-cache")
  48. }
  49. }
  50. m.Use(httpstatic.Static(
  51. path.Join(setting.StaticRootPath, dir),
  52. httpstatic.StaticOptions{
  53. SkipLogging: true,
  54. Prefix: prefix,
  55. AddHeaders: headers,
  56. },
  57. ))
  58. }
  59. func StartServer() {
  60. var err error
  61. m := newMacaron()
  62. api.Register(m)
  63. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  64. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  65. switch setting.Protocol {
  66. case setting.HTTP:
  67. err = http.ListenAndServe(listenAddr, m)
  68. case setting.HTTPS:
  69. err = http.ListenAndServeTLS(listenAddr, setting.CertFile, setting.KeyFile, m)
  70. default:
  71. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  72. }
  73. if err != nil {
  74. log.Fatal(4, "Fail to start server: %v", err)
  75. }
  76. }