api_dataproxy.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package api
  2. import (
  3. "net/http"
  4. "net/http/httputil"
  5. "net/url"
  6. "strings"
  7. "github.com/torkelo/grafana-pro/pkg/bus"
  8. "github.com/torkelo/grafana-pro/pkg/middleware"
  9. m "github.com/torkelo/grafana-pro/pkg/models"
  10. )
  11. func singleJoiningSlash(a, b string) string {
  12. aslash := strings.HasSuffix(a, "/")
  13. bslash := strings.HasPrefix(b, "/")
  14. switch {
  15. case aslash && bslash:
  16. return a + b[1:]
  17. case !aslash && !bslash:
  18. return a + "/" + b
  19. }
  20. return a + b
  21. }
  22. func NewReverseProxy(target *url.URL, proxyPath string) *httputil.ReverseProxy {
  23. targetQuery := target.RawQuery
  24. director := func(req *http.Request) {
  25. req.URL.Scheme = target.Scheme
  26. req.URL.Host = target.Host
  27. req.URL.Path = singleJoiningSlash(target.Path, proxyPath)
  28. if targetQuery == "" || req.URL.RawQuery == "" {
  29. req.URL.RawQuery = targetQuery + req.URL.RawQuery
  30. } else {
  31. req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
  32. }
  33. }
  34. return &httputil.ReverseProxy{Director: director}
  35. }
  36. // TODO: need to cache datasources
  37. func ProxyDataSourceRequest(c *middleware.Context) {
  38. id := c.ParamsInt64(":id")
  39. query := m.GetDataSourceByIdQuery{
  40. Id: id,
  41. AccountId: c.GetAccountId(),
  42. }
  43. err := bus.Dispatch(&query)
  44. if err != nil {
  45. c.JsonApiErr(500, "Unable to load datasource meta data", err)
  46. }
  47. proxyPath := c.Params("*")
  48. url, _ := url.Parse(query.Result.Url)
  49. proxy := NewReverseProxy(url, proxyPath)
  50. proxy.ServeHTTP(c.RW(), c.Req.Request)
  51. }