api_config.go 1.5 KB

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