web.go 2.3 KB

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