web.go 2.1 KB

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