Browse Source

Merge pull request #13326 from ryantxu/proxy-slash

Keep trailing slash for datasource proxy requests
Marcus Efraimsson 7 years ago
parent
commit
2b1e4d001a
3 changed files with 51 additions and 1 deletions
  1. 15 1
      pkg/api/dataproxy.go
  2. 19 0
      pkg/api/dataproxy_test.go
  3. 17 0
      pkg/api/pluginproxy/ds_proxy_test.go

+ 15 - 1
pkg/api/dataproxy.go

@@ -51,7 +51,21 @@ func (hs *HTTPServer) ProxyDataSourceRequest(c *m.ReqContext) {
 		return
 	}
 
-	proxyPath := c.Params("*")
+	// macaron does not include trailing slashes when resolving a wildcard path
+	proxyPath := ensureProxyPathTrailingSlash(c.Req.URL.Path, c.Params("*"))
+
 	proxy := pluginproxy.NewDataSourceProxy(ds, plugin, c, proxyPath)
 	proxy.HandleRequest()
 }
+
+// ensureProxyPathTrailingSlash Check for a trailing slash in original path and makes
+// sure that a trailing slash is added to proxy path, if not already exists.
+func ensureProxyPathTrailingSlash(originalPath, proxyPath string) string {
+	if len(proxyPath) > 1 {
+		if originalPath[len(originalPath)-1] == '/' && proxyPath[len(proxyPath)-1] != '/' {
+			return proxyPath + "/"
+		}
+	}
+
+	return proxyPath
+}

+ 19 - 0
pkg/api/dataproxy_test.go

@@ -0,0 +1,19 @@
+package api
+
+import (
+	"testing"
+
+	. "github.com/smartystreets/goconvey/convey"
+)
+
+func TestDataProxy(t *testing.T) {
+	Convey("Data proxy test", t, func() {
+		Convey("Should append trailing slash to proxy path if original path has a trailing slash", func() {
+			So(ensureProxyPathTrailingSlash("/api/datasources/proxy/6/api/v1/query_range/", "api/v1/query_range/"), ShouldEqual, "api/v1/query_range/")
+		})
+
+		Convey("Should not append trailing slash to proxy path if original path doesn't have a trailing slash", func() {
+			So(ensureProxyPathTrailingSlash("/api/datasources/proxy/6/api/v1/query_range", "api/v1/query_range"), ShouldEqual, "api/v1/query_range")
+		})
+	})
+}

+ 17 - 0
pkg/api/pluginproxy/ds_proxy_test.go

@@ -362,6 +362,23 @@ func TestDSRouteRule(t *testing.T) {
 			})
 		})
 
+		Convey("When proxying a custom datasource", func() {
+			plugin := &plugins.DataSourcePlugin{}
+			ds := &m.DataSource{
+				Type: "custom-datasource",
+				Url:  "http://host/root/",
+			}
+			ctx := &m.ReqContext{}
+			proxy := NewDataSourceProxy(ds, plugin, ctx, "/path/to/folder/")
+			req, err := http.NewRequest(http.MethodGet, "http://grafana.com/sub", nil)
+			So(err, ShouldBeNil)
+
+			proxy.getDirector()(req)
+
+			Convey("Shoudl keep user request (including trailing slash)", func() {
+				So(req.URL.String(), ShouldEqual, "http://host/root/path/to/folder/")
+			})
+		})
 	})
 }