api.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package httpApi
  2. import (
  3. "html/template"
  4. log "github.com/alecthomas/log4go"
  5. "github.com/gin-gonic/gin"
  6. "github.com/torkelo/grafana-pro/backend/models"
  7. "github.com/torkelo/grafana-pro/backend/stores"
  8. )
  9. type HttpServer struct {
  10. port string
  11. shutdown chan bool
  12. store stores.Store
  13. }
  14. func NewHttpServer(port string, store stores.Store) *HttpServer {
  15. self := &HttpServer{}
  16. self.port = port
  17. self.store = store
  18. return self
  19. }
  20. func CacheHeadersMiddleware() gin.HandlerFunc {
  21. return func(c *gin.Context) {
  22. c.Writer.Header().Add("Cache-Control", "max-age=0, public, must-revalidate, proxy-revalidate")
  23. }
  24. }
  25. func (self *HttpServer) ListenAndServe() {
  26. log.Info("Starting Http Listener on port %v", self.port)
  27. defer func() { self.shutdown <- true }()
  28. r := gin.Default()
  29. r.Use(CacheHeadersMiddleware())
  30. templates := template.New("templates")
  31. templates.Delims("[[", "]]")
  32. templates.ParseFiles("./views/index.html")
  33. r.SetHTMLTemplate(templates)
  34. r.GET("/", self.index)
  35. r.GET("/api/dashboards/:id", self.getDashboard)
  36. r.GET("/api/search/", self.search)
  37. r.POST("/api/dashboard", self.postDashboard)
  38. r.Static("/public", "./public")
  39. r.Static("/app", "./public/app")
  40. r.Static("/img", "./public/img")
  41. r.Run(":" + self.port)
  42. }
  43. type IndexViewModel struct {
  44. Title string
  45. }
  46. func (self *HttpServer) index(c *gin.Context) {
  47. c.HTML(200, "index.html", &IndexViewModel{Title: "hello from go"})
  48. }
  49. type ErrorRsp struct {
  50. Message string `json:"message"`
  51. }
  52. func (self *HttpServer) getDashboard(c *gin.Context) {
  53. id := c.Params.ByName("id")
  54. dash, err := self.store.GetById(id)
  55. if err != nil {
  56. c.JSON(404, &ErrorRsp{Message: "Dashboard not found"})
  57. return
  58. }
  59. c.JSON(200, dash.Data)
  60. }
  61. func (self *HttpServer) search(c *gin.Context) {
  62. query := c.Params.ByName("q")
  63. results, err := self.store.Query(query)
  64. if err != nil {
  65. c.JSON(500, &ErrorRsp{Message: "Search error"})
  66. return
  67. }
  68. c.JSON(200, results)
  69. }
  70. func (self *HttpServer) postDashboard(c *gin.Context) {
  71. var command saveDashboardCommand
  72. if c.EnsureBody(&command) {
  73. err := self.store.Save(&models.Dashboard{Data: command.Dashboard})
  74. if err == nil {
  75. c.JSON(200, gin.H{"status": "saved"})
  76. return
  77. }
  78. }
  79. c.JSON(500, gin.H{"error": "bad request"})
  80. }