web.go 2.4 KB

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