dataproxy.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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{
  42. Id: id,
  43. OrgId: c.OrgId,
  44. }
  45. err := bus.Dispatch(&query)
  46. if err != nil {
  47. c.JsonApiErr(500, "Unable to load datasource meta data", err)
  48. }
  49. proxyPath := c.Params("*")
  50. proxy := NewReverseProxy(&query.Result, proxyPath)
  51. proxy.ServeHTTP(c.RW(), c.Req.Request)
  52. }