dataproxy.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. reqQueryVals := req.URL.Query()
  17. if ds.Type == m.DS_INFLUXDB {
  18. req.URL.Path = util.JoinUrlFragments(target.Path, "db/"+ds.Database+"/"+proxyPath)
  19. reqQueryVals.Add("u", ds.User)
  20. reqQueryVals.Add("p", ds.Password)
  21. req.URL.RawQuery = reqQueryVals.Encode()
  22. } else {
  23. req.URL.Path = util.JoinUrlFragments(target.Path, proxyPath)
  24. }
  25. }
  26. return &httputil.ReverseProxy{Director: director}
  27. }
  28. // TODO: need to cache datasources
  29. func ProxyDataSourceRequest(c *middleware.Context) {
  30. id := c.ParamsInt64(":id")
  31. query := m.GetDataSourceByIdQuery{
  32. Id: id,
  33. AccountId: c.AccountId,
  34. }
  35. err := bus.Dispatch(&query)
  36. if err != nil {
  37. c.JsonApiErr(500, "Unable to load datasource meta data", err)
  38. }
  39. proxyPath := c.Params("*")
  40. proxy := NewReverseProxy(&query.Result, proxyPath)
  41. proxy.ServeHTTP(c.RW(), c.Req.Request)
  42. }