web.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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/codegangsta/cli"
  10. "github.com/macaron-contrib/session"
  11. "github.com/torkelo/grafana-pro/pkg/api"
  12. "github.com/torkelo/grafana-pro/pkg/log"
  13. "github.com/torkelo/grafana-pro/pkg/middleware"
  14. "github.com/torkelo/grafana-pro/pkg/setting"
  15. "github.com/torkelo/grafana-pro/pkg/social"
  16. "github.com/torkelo/grafana-pro/pkg/stores/sqlstore"
  17. )
  18. var CmdWeb = cli.Command{
  19. Name: "web",
  20. Usage: "grafana web",
  21. Description: "Starts Grafana backend & web server",
  22. Action: runWeb,
  23. Flags: []cli.Flag{
  24. cli.StringFlag{
  25. Name: "config",
  26. Value: "grafana.ini",
  27. Usage: "path to config file",
  28. },
  29. },
  30. }
  31. func newMacaron() *macaron.Macaron {
  32. m := macaron.New()
  33. m.Use(middleware.Logger())
  34. m.Use(macaron.Recovery())
  35. mapStatic(m, "", "public")
  36. mapStatic(m, "app", "app")
  37. mapStatic(m, "css", "css")
  38. mapStatic(m, "img", "img")
  39. mapStatic(m, "font", "font")
  40. m.Use(session.Sessioner(setting.SessionOptions))
  41. m.Use(macaron.Renderer(macaron.RenderOptions{
  42. Directory: path.Join(setting.StaticRootPath, "views"),
  43. IndentJSON: macaron.Env != macaron.PROD,
  44. Delims: macaron.Delims{Left: "[[", Right: "]]"},
  45. }))
  46. m.Use(middleware.GetContextHandler())
  47. return m
  48. }
  49. func mapStatic(m *macaron.Macaron, dir string, prefix string) {
  50. m.Use(macaron.Static(
  51. path.Join(setting.StaticRootPath, dir),
  52. macaron.StaticOptions{
  53. SkipLogging: true,
  54. Prefix: prefix,
  55. },
  56. ))
  57. }
  58. func runWeb(c *cli.Context) {
  59. log.Info("Starting Grafana 2.0-alpha")
  60. setting.NewConfigContext()
  61. setting.InitServices()
  62. social.NewOAuthService()
  63. sqlstore.Init()
  64. sqlstore.NewEngine()
  65. m := newMacaron()
  66. api.Register(m)
  67. var err error
  68. listenAddr := fmt.Sprintf("%s:%s", setting.HttpAddr, setting.HttpPort)
  69. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubUrl)
  70. switch setting.Protocol {
  71. case setting.HTTP:
  72. err = http.ListenAndServe(listenAddr, m)
  73. case setting.HTTPS:
  74. err = http.ListenAndServeTLS(listenAddr, setting.CertFile, setting.KeyFile, m)
  75. default:
  76. log.Fatal(4, "Invalid protocol: %s", setting.Protocol)
  77. }
  78. if err != nil {
  79. log.Fatal(4, "Fail to start server: %v", err)
  80. }
  81. }