dataproxy.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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_08 {
  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 if ds.Type == m.DS_INFLUXDB {
  24. req.URL.Path = util.JoinUrlFragments(target.Path, proxyPath)
  25. reqQueryVals.Add("db", ds.Database)
  26. reqQueryVals.Add("u", ds.User)
  27. reqQueryVals.Add("p", ds.Password)
  28. req.URL.RawQuery = reqQueryVals.Encode()
  29. } else {
  30. req.URL.Path = util.JoinUrlFragments(target.Path, proxyPath)
  31. }
  32. if ds.BasicAuth {
  33. req.Header.Add("Authorization", util.GetBasicAuthHeader(ds.BasicAuthUser, ds.BasicAuthPassword))
  34. }
  35. }
  36. return &httputil.ReverseProxy{Director: director}
  37. }
  38. // TODO: need to cache datasources
  39. func ProxyDataSourceRequest(c *middleware.Context) {
  40. id := c.ParamsInt64(":id")
  41. query := m.GetDataSourceByIdQuery{Id: id, OrgId: c.OrgId}
  42. if err := bus.Dispatch(&query); err != nil {
  43. c.JsonApiErr(500, "Unable to load datasource meta data", err)
  44. return
  45. }
  46. proxyPath := c.Params("*")
  47. proxy := NewReverseProxy(&query.Result, proxyPath)
  48. proxy.ServeHTTP(c.RW(), c.Req.Request)
  49. }