web.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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, setting.StaticRootPath, "", "public")
  24. mapStatic(m, setting.StaticRootPath, "app", "app")
  25. mapStatic(m, setting.StaticRootPath, "css", "css")
  26. mapStatic(m, setting.StaticRootPath, "img", "img")
  27. mapStatic(m, setting.StaticRootPath, "fonts", "fonts")
  28. mapStatic(m, setting.StaticRootPath, "robots.txt", "robots.txt")
  29. mapStatic(m, setting.DataPath, "plugins", "_plugins")
  30. m.Use(macaron.Renderer(macaron.RenderOptions{
  31. Directory: path.Join(setting.StaticRootPath, "views"),
  32. IndentJSON: macaron.Env != macaron.PROD,
  33. Delims: macaron.Delims{Left: "[[", Right: "]]"},
  34. }))
  35. if setting.EnforceDomain {
  36. m.Use(middleware.ValidateHostHeader(setting.Domain))
  37. }
  38. m.Use(middleware.GetContextHandler())
  39. m.Use(middleware.Sessioner(&setting.SessionOptions))
  40. return m
  41. }
  42. func mapStatic(m *macaron.Macaron, rootDir string, dir string, prefix string) {
  43. headers := func(c *macaron.Context) {
  44. c.Resp.Header().Set("Cache-Control", "public, max-age=3600")
  45. }
  46. if setting.Env == setting.DEV {
  47. headers = func(c *macaron.Context) {
  48. c.Resp.Header().Set("Cache-Control", "max-age=0, must-revalidate, no-cache")
  49. }
  50. }
  51. m.Use(httpstatic.Static(
  52. path.Join(rootDir, dir),
  53. httpstatic.StaticOptions{
  54. SkipLogging: true,
  55. Prefix: prefix,
  56. AddHeaders: headers,
  57. },
  58. ))
  59. }
  60. func StartServer() {
  61. var err error
  62. m := newMacaron()
  63. api.Register(m)
  64. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  65. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  66. switch setting.Protocol {
  67. case setting.HTTP:
  68. err = http.ListenAndServe(listenAddr, m)
  69. case setting.HTTPS:
  70. err = http.ListenAndServeTLS(listenAddr, setting.CertFile, setting.KeyFile, m)
  71. default:
  72. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  73. }
  74. if err != nil {
  75. log.Fatal(4, "Fail to start server: %v", err)
  76. }
  77. }