dataproxy.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package api
  2. import (
  3. "net/http"
  4. "net/http/httputil"
  5. "net/url"
  6. "github.com/grafana/grafana/pkg/bus"
  7. "github.com/grafana/grafana/pkg/middleware"
  8. m "github.com/grafana/grafana/pkg/models"
  9. "github.com/grafana/grafana/pkg/util"
  10. )
  11. func NewReverseProxy(ds *m.DataSource, proxyPath string) *httputil.ReverseProxy {
  12. target, _ := url.Parse(ds.Url)
  13. director := func(req *http.Request) {
  14. req.URL.Scheme = target.Scheme
  15. req.URL.Host = target.Host
  16. req.Host = target.Host
  17. reqQueryVals := req.URL.Query()
  18. if ds.Type == m.DS_INFLUXDB {
  19. req.URL.Path = util.JoinUrlFragments(target.Path, "db/"+ds.Database+"/"+proxyPath)
  20. reqQueryVals.Add("u", ds.User)
  21. reqQueryVals.Add("p", ds.Password)
  22. req.URL.RawQuery = reqQueryVals.Encode()
  23. } else {
  24. req.URL.Path = util.JoinUrlFragments(target.Path, proxyPath)
  25. }
  26. }
  27. return &httputil.ReverseProxy{Director: director}
  28. }
  29. // TODO: need to cache datasources
  30. func ProxyDataSourceRequest(c *middleware.Context) {
  31. id := c.ParamsInt64(":id")
  32. query := m.GetDataSourceByIdQuery{
  33. Id: id,
  34. OrgId: c.OrgId,
  35. }
  36. err := bus.Dispatch(&query)
  37. if err != nil {
  38. c.JsonApiErr(500, "Unable to load datasource meta data", err)
  39. }
  40. proxyPath := c.Params("*")
  41. proxy := NewReverseProxy(&query.Result, proxyPath)
  42. proxy.ServeHTTP(c.RW(), c.Req.Request)
  43. }