mirror of https://github.com/grafana/grafana
Plugins: Support templated urls in routes (#16599)
This adds support for using templated/dynamic urls in routes. * refactor interpolateString into utils and add interpolation support for app plugin routes. * cleanup and add error check for url parse failure * add docs for interpolated route urls Closes #16835pull/16928/head
parent
336655a46a
commit
b07d0b1026
@ -0,0 +1,49 @@ |
||||
package pluginproxy |
||||
|
||||
import ( |
||||
"bytes" |
||||
"fmt" |
||||
"net/url" |
||||
"text/template" |
||||
|
||||
m "github.com/grafana/grafana/pkg/models" |
||||
"github.com/grafana/grafana/pkg/plugins" |
||||
) |
||||
|
||||
// InterpolateString accepts template data and return a string with substitutions
|
||||
func InterpolateString(text string, data templateData) (string, error) { |
||||
t, err := template.New("content").Parse(text) |
||||
if err != nil { |
||||
return "", fmt.Errorf("could not parse template %s", text) |
||||
} |
||||
|
||||
var contentBuf bytes.Buffer |
||||
err = t.Execute(&contentBuf, data) |
||||
if err != nil { |
||||
return "", fmt.Errorf("failed to execute template %s", text) |
||||
} |
||||
|
||||
return contentBuf.String(), nil |
||||
} |
||||
|
||||
// InterpolateURL accepts template data and return a string with substitutions
|
||||
func InterpolateURL(anURL *url.URL, route *plugins.AppPluginRoute, orgID int64, appID string) (*url.URL, error) { |
||||
query := m.GetPluginSettingByIdQuery{OrgId: orgID, PluginId: appID} |
||||
result, err := url.Parse(anURL.String()) |
||||
if query.Result != nil { |
||||
if len(query.Result.JsonData) > 0 { |
||||
data := templateData{ |
||||
JsonData: query.Result.JsonData, |
||||
} |
||||
interpolatedResult, err := InterpolateString(anURL.String(), data) |
||||
if err == nil { |
||||
result, err = url.Parse(interpolatedResult) |
||||
if err != nil { |
||||
return nil, fmt.Errorf("Error parsing plugin route url %v", err) |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
return result, err |
||||
} |
||||
@ -0,0 +1,21 @@ |
||||
package pluginproxy |
||||
|
||||
import ( |
||||
"testing" |
||||
|
||||
. "github.com/smartystreets/goconvey/convey" |
||||
) |
||||
|
||||
func TestInterpolateString(t *testing.T) { |
||||
Convey("When interpolating string", t, func() { |
||||
data := templateData{ |
||||
SecureJsonData: map[string]string{ |
||||
"Test": "0asd+asd", |
||||
}, |
||||
} |
||||
|
||||
interpolated, err := InterpolateString("{{.SecureJsonData.Test}}", data) |
||||
So(err, ShouldBeNil) |
||||
So(interpolated, ShouldEqual, "0asd+asd") |
||||
}) |
||||
} |
||||
Loading…
Reference in new issue