api_config.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package api
  2. import (
  3. "encoding/json"
  4. "strings"
  5. "github.com/torkelo/grafana-pro/pkg/bus"
  6. "github.com/torkelo/grafana-pro/pkg/middleware"
  7. m "github.com/torkelo/grafana-pro/pkg/models"
  8. )
  9. const configTemplate = `
  10. define(['settings'],
  11. function (Settings) {
  12. "use strict";
  13. return new Settings(%json%);
  14. });
  15. `
  16. type configJsTmplModel struct {
  17. DataSources []*m.DataSource
  18. }
  19. func renderConfig(data *configJsTmplModel) string {
  20. datasources := make(map[string]interface{})
  21. for _, ds := range data.DataSources {
  22. url := ds.Url
  23. if ds.Access == m.DS_ACCESS_PROXY {
  24. url = "/api/datasources/proxy/" + ds.Name
  25. }
  26. datasources[ds.Name] = map[string]interface{}{
  27. "type": ds.Type,
  28. "url": url,
  29. }
  30. }
  31. jsonObj := map[string]interface{}{
  32. "datasources": datasources,
  33. }
  34. buff, _ := json.Marshal(jsonObj)
  35. return strings.Replace(configTemplate, "%json%", string(buff), 1)
  36. }
  37. func GetConfigJS(c *middleware.Context) {
  38. query := m.GetDataSourcesQuery{AccountId: c.GetAccountId()}
  39. err := bus.Dispatch(&query)
  40. if err != nil {
  41. c.Handle(500, "cold not load data sources", err)
  42. return
  43. }
  44. vm := configJsTmplModel{DataSources: query.Result}
  45. configStr := renderConfig(&vm)
  46. if err != nil {
  47. c.Handle(500, "Failed to generate config.js", err)
  48. return
  49. }
  50. c.Header().Set("Content-Type", "text/javascript; charset=UTF-8")
  51. c.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  52. c.Header().Set("Pragma", "no-cache")
  53. c.Header().Set("Expires", "0")
  54. c.WriteHeader(200)
  55. c.Write([]byte(configStr))
  56. }