web.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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: "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(setting.SessionOptions))
  33. m.Use(macaron.Renderer(macaron.RenderOptions{
  34. Directory: path.Join(setting.StaticRootPath, "views"),
  35. IndentJSON: macaron.Env != macaron.PROD,
  36. Delims: macaron.Delims{Left: "[[", Right: "]]"},
  37. }))
  38. m.Use(middleware.GetContextHandler())
  39. return m
  40. }
  41. func mapStatic(m *macaron.Macaron, dir string, prefix string) {
  42. m.Use(macaron.Static(
  43. path.Join(setting.StaticRootPath, dir),
  44. macaron.StaticOptions{
  45. SkipLogging: true,
  46. Prefix: prefix,
  47. },
  48. ))
  49. }
  50. func runWeb(*cli.Context) {
  51. log.Info("Starting Grafana-Pro v.2-alpha")
  52. setting.NewConfigContext()
  53. setting.InitServices()
  54. social.NewOAuthService()
  55. sqlstore.Init()
  56. sqlstore.NewEngine()
  57. m := newMacaron()
  58. api.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. }