Chore: pass url parameters through context.Context (#38826)

* pass url parameters through context.Context

* fix url param names without colon prefix

* change context params to vars

* replace url vars in tests using new api

* rename vars to params

* add some comments

* rename seturlvars to seturlparams
pull/38404/head
Serge Zaitsev 4 years ago committed by GitHub
parent fb1c31e1b6
commit 063160aae2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 7
      pkg/api/alerting.go
  2. 2
      pkg/api/app_routes.go
  3. 3
      pkg/api/avatar/avatar.go
  4. 7
      pkg/api/dashboard.go
  5. 7
      pkg/api/dashboard_snapshot.go
  6. 13
      pkg/api/datasources.go
  7. 9
      pkg/api/folder.go
  8. 5
      pkg/api/folder_permission.go
  9. 3
      pkg/api/grafana_com_proxy.go
  10. 3
      pkg/api/ldap_debug.go
  11. 3
      pkg/api/login_oauth.go
  12. 3
      pkg/api/org.go
  13. 5
      pkg/api/org_invite.go
  14. 27
      pkg/api/plugins.go
  15. 5
      pkg/api/quota.go
  16. 3
      pkg/api/render.go
  17. 3
      pkg/api/short_url.go
  18. 2
      pkg/macaron/binding/binding.go
  19. 25
      pkg/macaron/context.go
  20. 4
      pkg/macaron/inject.go
  21. 15
      pkg/macaron/macaron.go
  22. 9
      pkg/macaron/router.go
  23. 10
      pkg/macaron/tree.go
  24. 5
      pkg/plugins/backendplugin/pluginextensionv2/rendererv2.pb.go
  25. 2
      pkg/services/accesscontrol/middleware/middleware.go
  26. 7
      pkg/services/libraryelements/api.go
  27. 5
      pkg/services/libraryelements/database.go
  28. 7
      pkg/services/libraryelements/libraryelements_delete_test.go
  29. 17
      pkg/services/libraryelements/libraryelements_get_test.go
  30. 35
      pkg/services/libraryelements/libraryelements_patch_test.go
  31. 19
      pkg/services/libraryelements/libraryelements_permissions_test.go
  32. 5
      pkg/services/live/live.go
  33. 7
      pkg/services/live/pushhttp/push.go
  34. 5
      pkg/services/ngalert/api/api_alertmanager.go
  35. 15
      pkg/services/ngalert/api/api_ruler.go
  36. 3
      pkg/services/ngalert/api/api_testing.go
  37. 5
      pkg/services/ngalert/api/lotex_am.go
  38. 2
      pkg/services/ngalert/api/lotex_prom.go
  39. 17
      pkg/services/ngalert/api/lotex_ruler.go
  40. 4
      pkg/services/ngalert/api/util.go
  41. 2
      pkg/services/ngalert/metrics/ngalert.go

@ -14,6 +14,7 @@ import (
"github.com/grafana/grafana/pkg/services/ngalert/notifier" "github.com/grafana/grafana/pkg/services/ngalert/notifier"
"github.com/grafana/grafana/pkg/services/search" "github.com/grafana/grafana/pkg/services/search"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
macaron "gopkg.in/macaron.v1"
) )
func ValidateOrgAlert(c *models.ReqContext) { func ValidateOrgAlert(c *models.ReqContext) {
@ -255,7 +256,7 @@ func GetAlertNotificationByID(c *models.ReqContext) response.Response {
func GetAlertNotificationByUID(c *models.ReqContext) response.Response { func GetAlertNotificationByUID(c *models.ReqContext) response.Response {
query := &models.GetAlertNotificationsWithUidQuery{ query := &models.GetAlertNotificationsWithUidQuery{
OrgId: c.OrgId, OrgId: c.OrgId,
Uid: c.Params("uid"), Uid: macaron.Params(c.Req)[":uid"],
} }
if query.Uid == "" { if query.Uid == "" {
@ -315,7 +316,7 @@ func UpdateAlertNotification(c *models.ReqContext, cmd models.UpdateAlertNotific
func UpdateAlertNotificationByUID(c *models.ReqContext, cmd models.UpdateAlertNotificationWithUidCommand) response.Response { func UpdateAlertNotificationByUID(c *models.ReqContext, cmd models.UpdateAlertNotificationWithUidCommand) response.Response {
cmd.OrgId = c.OrgId cmd.OrgId = c.OrgId
cmd.Uid = c.Params("uid") cmd.Uid = macaron.Params(c.Req)[":uid"]
err := fillWithSecureSettingsDataByUID(&cmd) err := fillWithSecureSettingsDataByUID(&cmd)
if err != nil { if err != nil {
@ -408,7 +409,7 @@ func DeleteAlertNotification(c *models.ReqContext) response.Response {
func DeleteAlertNotificationByUID(c *models.ReqContext) response.Response { func DeleteAlertNotificationByUID(c *models.ReqContext) response.Response {
cmd := models.DeleteAlertNotificationWithUidCommand{ cmd := models.DeleteAlertNotificationWithUidCommand{
OrgId: c.OrgId, OrgId: c.OrgId,
Uid: c.Params("uid"), Uid: macaron.Params(c.Req)[":uid"],
} }
if err := bus.Dispatch(&cmd); err != nil { if err := bus.Dispatch(&cmd); err != nil {

@ -58,7 +58,7 @@ func (hs *HTTPServer) initAppPluginRoutes(r *macaron.Macaron) {
func AppPluginRoute(route *plugins.AppPluginRoute, appID string, hs *HTTPServer) macaron.Handler { func AppPluginRoute(route *plugins.AppPluginRoute, appID string, hs *HTTPServer) macaron.Handler {
return func(c *models.ReqContext) { return func(c *models.ReqContext) {
path := c.Params("*") path := macaron.Params(c.Req)["*"]
proxy := pluginproxy.NewApiPluginProxy(c, path, route, appID, hs.Cfg) proxy := pluginproxy.NewApiPluginProxy(c, path, route, appID, hs.Cfg)
proxy.Transport = pluginProxyTransport proxy.Transport = pluginProxyTransport

@ -23,6 +23,7 @@ import (
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"gopkg.in/macaron.v1"
gocache "github.com/patrickmn/go-cache" gocache "github.com/patrickmn/go-cache"
) )
@ -77,7 +78,7 @@ type CacheServer struct {
var validMD5 = regexp.MustCompile("^[a-fA-F0-9]{32}$") var validMD5 = regexp.MustCompile("^[a-fA-F0-9]{32}$")
func (a *CacheServer) Handler(ctx *models.ReqContext) { func (a *CacheServer) Handler(ctx *models.ReqContext) {
hash := ctx.Params("hash") hash := macaron.Params(ctx.Req)[":hash"]
if len(hash) != 32 || !validMD5.MatchString(hash) { if len(hash) != 32 || !validMD5.MatchString(hash) {
ctx.JsonApiErr(404, "Avatar not found", nil) ctx.JsonApiErr(404, "Avatar not found", nil)

@ -11,6 +11,7 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
macaron "gopkg.in/macaron.v1"
"github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
@ -70,7 +71,7 @@ func (hs *HTTPServer) TrimDashboard(c *models.ReqContext, cmd models.TrimDashboa
} }
func (hs *HTTPServer) GetDashboard(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetDashboard(c *models.ReqContext) response.Response {
uid := c.Params(":uid") uid := macaron.Params(c.Req)[":uid"]
dash, rsp := getDashboardHelper(c.Req.Context(), c.OrgId, 0, uid) dash, rsp := getDashboardHelper(c.Req.Context(), c.OrgId, 0, uid)
if rsp != nil { if rsp != nil {
return rsp return rsp
@ -214,7 +215,7 @@ func getDashboardHelper(ctx context.Context, orgID int64, id int64, uid string)
} }
func (hs *HTTPServer) DeleteDashboardBySlug(c *models.ReqContext) response.Response { func (hs *HTTPServer) DeleteDashboardBySlug(c *models.ReqContext) response.Response {
query := models.GetDashboardsBySlugQuery{OrgId: c.OrgId, Slug: c.Params(":slug")} query := models.GetDashboardsBySlugQuery{OrgId: c.OrgId, Slug: macaron.Params(c.Req)[":slug"]}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
return response.Error(500, "Failed to retrieve dashboards by slug", err) return response.Error(500, "Failed to retrieve dashboards by slug", err)
@ -232,7 +233,7 @@ func (hs *HTTPServer) DeleteDashboardByUID(c *models.ReqContext) response.Respon
} }
func (hs *HTTPServer) deleteDashboard(c *models.ReqContext) response.Response { func (hs *HTTPServer) deleteDashboard(c *models.ReqContext) response.Response {
dash, rsp := getDashboardHelper(c.Req.Context(), c.OrgId, 0, c.Params(":uid")) dash, rsp := getDashboardHelper(c.Req.Context(), c.OrgId, 0, macaron.Params(c.Req)[":uid"])
if rsp != nil { if rsp != nil {
return rsp return rsp
} }

@ -16,6 +16,7 @@ import (
"github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
macaron "gopkg.in/macaron.v1"
) )
var client = &http.Client{ var client = &http.Client{
@ -145,7 +146,7 @@ func CreateDashboardSnapshot(c *models.ReqContext, cmd models.CreateDashboardSna
// GET /api/snapshots/:key // GET /api/snapshots/:key
func GetDashboardSnapshot(c *models.ReqContext) response.Response { func GetDashboardSnapshot(c *models.ReqContext) response.Response {
key := c.Params(":key") key := macaron.Params(c.Req)[":key"]
query := &models.GetDashboardSnapshotQuery{Key: key} query := &models.GetDashboardSnapshotQuery{Key: key}
err := bus.Dispatch(query) err := bus.Dispatch(query)
@ -209,7 +210,7 @@ func deleteExternalDashboardSnapshot(externalUrl string) error {
// GET /api/snapshots-delete/:deleteKey // GET /api/snapshots-delete/:deleteKey
func DeleteDashboardSnapshotByDeleteKey(c *models.ReqContext) response.Response { func DeleteDashboardSnapshotByDeleteKey(c *models.ReqContext) response.Response {
key := c.Params(":deleteKey") key := macaron.Params(c.Req)[":deleteKey"]
query := &models.GetDashboardSnapshotQuery{DeleteKey: key} query := &models.GetDashboardSnapshotQuery{DeleteKey: key}
@ -239,7 +240,7 @@ func DeleteDashboardSnapshotByDeleteKey(c *models.ReqContext) response.Response
// DELETE /api/snapshots/:key // DELETE /api/snapshots/:key
func DeleteDashboardSnapshot(c *models.ReqContext) response.Response { func DeleteDashboardSnapshot(c *models.ReqContext) response.Response {
key := c.Params(":key") key := macaron.Params(c.Req)[":key"]
query := &models.GetDashboardSnapshotQuery{Key: key} query := &models.GetDashboardSnapshotQuery{Key: key}

@ -14,6 +14,7 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins/adapters" "github.com/grafana/grafana/pkg/plugins/adapters"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
macaron "gopkg.in/macaron.v1"
"github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana-plugin-sdk-go/backend"
) )
@ -117,7 +118,7 @@ func (hs *HTTPServer) DeleteDataSourceById(c *models.ReqContext) response.Respon
// GET /api/datasources/uid/:uid // GET /api/datasources/uid/:uid
func GetDataSourceByUID(c *models.ReqContext) response.Response { func GetDataSourceByUID(c *models.ReqContext) response.Response {
ds, err := getRawDataSourceByUID(c.Params(":uid"), c.OrgId) ds, err := getRawDataSourceByUID(macaron.Params(c.Req)[":uid"], c.OrgId)
if err != nil { if err != nil {
if errors.Is(err, models.ErrDataSourceNotFound) { if errors.Is(err, models.ErrDataSourceNotFound) {
@ -132,7 +133,7 @@ func GetDataSourceByUID(c *models.ReqContext) response.Response {
// DELETE /api/datasources/uid/:uid // DELETE /api/datasources/uid/:uid
func (hs *HTTPServer) DeleteDataSourceByUID(c *models.ReqContext) response.Response { func (hs *HTTPServer) DeleteDataSourceByUID(c *models.ReqContext) response.Response {
uid := c.Params(":uid") uid := macaron.Params(c.Req)[":uid"]
if uid == "" { if uid == "" {
return response.Error(400, "Missing datasource uid", nil) return response.Error(400, "Missing datasource uid", nil)
@ -163,7 +164,7 @@ func (hs *HTTPServer) DeleteDataSourceByUID(c *models.ReqContext) response.Respo
} }
func (hs *HTTPServer) DeleteDataSourceByName(c *models.ReqContext) response.Response { func (hs *HTTPServer) DeleteDataSourceByName(c *models.ReqContext) response.Response {
name := c.Params(":name") name := macaron.Params(c.Req)[":name"]
if name == "" { if name == "" {
return response.Error(400, "Missing valid datasource name", nil) return response.Error(400, "Missing valid datasource name", nil)
@ -328,7 +329,7 @@ func getRawDataSourceByUID(uid string, orgID int64) (*models.DataSource, error)
// Get /api/datasources/name/:name // Get /api/datasources/name/:name
func GetDataSourceByName(c *models.ReqContext) response.Response { func GetDataSourceByName(c *models.ReqContext) response.Response {
query := models.GetDataSourceQuery{Name: c.Params(":name"), OrgId: c.OrgId} query := models.GetDataSourceQuery{Name: macaron.Params(c.Req)[":name"], OrgId: c.OrgId}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
if errors.Is(err, models.ErrDataSourceNotFound) { if errors.Is(err, models.ErrDataSourceNotFound) {
@ -343,7 +344,7 @@ func GetDataSourceByName(c *models.ReqContext) response.Response {
// Get /api/datasources/id/:name // Get /api/datasources/id/:name
func GetDataSourceIdByName(c *models.ReqContext) response.Response { func GetDataSourceIdByName(c *models.ReqContext) response.Response {
query := models.GetDataSourceQuery{Name: c.Params(":name"), OrgId: c.OrgId} query := models.GetDataSourceQuery{Name: macaron.Params(c.Req)[":name"], OrgId: c.OrgId}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
if errors.Is(err, models.ErrDataSourceNotFound) { if errors.Is(err, models.ErrDataSourceNotFound) {
@ -391,7 +392,7 @@ func (hs *HTTPServer) CallDatasourceResource(c *models.ReqContext) {
PluginID: plugin.Id, PluginID: plugin.Id,
DataSourceInstanceSettings: dsInstanceSettings, DataSourceInstanceSettings: dsInstanceSettings,
} }
hs.BackendPluginManager.CallResource(pCtx, c, c.Params("*")) hs.BackendPluginManager.CallResource(pCtx, c, macaron.Params(c.Req)["*"])
} }
func convertModelToDtos(ds *models.DataSource) dtos.DataSource { func convertModelToDtos(ds *models.DataSource) dtos.DataSource {

@ -13,6 +13,7 @@ import (
"github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/services/libraryelements" "github.com/grafana/grafana/pkg/services/libraryelements"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
macaron "gopkg.in/macaron.v1"
) )
func (hs *HTTPServer) GetFolders(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetFolders(c *models.ReqContext) response.Response {
@ -38,7 +39,7 @@ func (hs *HTTPServer) GetFolders(c *models.ReqContext) response.Response {
func (hs *HTTPServer) GetFolderByUID(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetFolderByUID(c *models.ReqContext) response.Response {
s := dashboards.NewFolderService(c.OrgId, c.SignedInUser, hs.SQLStore) s := dashboards.NewFolderService(c.OrgId, c.SignedInUser, hs.SQLStore)
folder, err := s.GetFolderByUID(c.Req.Context(), c.Params(":uid")) folder, err := s.GetFolderByUID(c.Req.Context(), macaron.Params(c.Req)[":uid"])
if err != nil { if err != nil {
return apierrors.ToFolderErrorResponse(err) return apierrors.ToFolderErrorResponse(err)
} }
@ -78,7 +79,7 @@ func (hs *HTTPServer) CreateFolder(c *models.ReqContext, cmd models.CreateFolder
func (hs *HTTPServer) UpdateFolder(c *models.ReqContext, cmd models.UpdateFolderCommand) response.Response { func (hs *HTTPServer) UpdateFolder(c *models.ReqContext, cmd models.UpdateFolderCommand) response.Response {
s := dashboards.NewFolderService(c.OrgId, c.SignedInUser, hs.SQLStore) s := dashboards.NewFolderService(c.OrgId, c.SignedInUser, hs.SQLStore)
err := s.UpdateFolder(c.Req.Context(), c.Params(":uid"), &cmd) err := s.UpdateFolder(c.Req.Context(), macaron.Params(c.Req)[":uid"], &cmd)
if err != nil { if err != nil {
return apierrors.ToFolderErrorResponse(err) return apierrors.ToFolderErrorResponse(err)
} }
@ -89,7 +90,7 @@ func (hs *HTTPServer) UpdateFolder(c *models.ReqContext, cmd models.UpdateFolder
func (hs *HTTPServer) DeleteFolder(c *models.ReqContext) response.Response { // temporarily adding this function to HTTPServer, will be removed from HTTPServer when librarypanels featuretoggle is removed func (hs *HTTPServer) DeleteFolder(c *models.ReqContext) response.Response { // temporarily adding this function to HTTPServer, will be removed from HTTPServer when librarypanels featuretoggle is removed
s := dashboards.NewFolderService(c.OrgId, c.SignedInUser, hs.SQLStore) s := dashboards.NewFolderService(c.OrgId, c.SignedInUser, hs.SQLStore)
err := hs.LibraryElementService.DeleteLibraryElementsInFolder(c, c.Params(":uid")) err := hs.LibraryElementService.DeleteLibraryElementsInFolder(c, macaron.Params(c.Req)[":uid"])
if err != nil { if err != nil {
if errors.Is(err, libraryelements.ErrFolderHasConnectedLibraryElements) { if errors.Is(err, libraryelements.ErrFolderHasConnectedLibraryElements) {
return response.Error(403, "Folder could not be deleted because it contains library elements in use", err) return response.Error(403, "Folder could not be deleted because it contains library elements in use", err)
@ -97,7 +98,7 @@ func (hs *HTTPServer) DeleteFolder(c *models.ReqContext) response.Response { //
return apierrors.ToFolderErrorResponse(err) return apierrors.ToFolderErrorResponse(err)
} }
f, err := s.DeleteFolder(c.Req.Context(), c.Params(":uid"), c.QueryBool("forceDeleteRules")) f, err := s.DeleteFolder(c.Req.Context(), macaron.Params(c.Req)[":uid"], c.QueryBool("forceDeleteRules"))
if err != nil { if err != nil {
return apierrors.ToFolderErrorResponse(err) return apierrors.ToFolderErrorResponse(err)
} }

@ -11,11 +11,12 @@ import (
"github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/guardian"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
macaron "gopkg.in/macaron.v1"
) )
func (hs *HTTPServer) GetFolderPermissionList(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetFolderPermissionList(c *models.ReqContext) response.Response {
s := dashboards.NewFolderService(c.OrgId, c.SignedInUser, hs.SQLStore) s := dashboards.NewFolderService(c.OrgId, c.SignedInUser, hs.SQLStore)
folder, err := s.GetFolderByUID(c.Req.Context(), c.Params(":uid")) folder, err := s.GetFolderByUID(c.Req.Context(), macaron.Params(c.Req)[":uid"])
if err != nil { if err != nil {
return apierrors.ToFolderErrorResponse(err) return apierrors.ToFolderErrorResponse(err)
@ -63,7 +64,7 @@ func (hs *HTTPServer) UpdateFolderPermissions(c *models.ReqContext, apiCmd dtos.
} }
s := dashboards.NewFolderService(c.OrgId, c.SignedInUser, hs.SQLStore) s := dashboards.NewFolderService(c.OrgId, c.SignedInUser, hs.SQLStore)
folder, err := s.GetFolderByUID(c.Req.Context(), c.Params(":uid")) folder, err := s.GetFolderByUID(c.Req.Context(), macaron.Params(c.Req)[":uid"])
if err != nil { if err != nil {
return apierrors.ToFolderErrorResponse(err) return apierrors.ToFolderErrorResponse(err)
} }

@ -10,6 +10,7 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
macaron "gopkg.in/macaron.v1"
) )
var grafanaComProxyTransport = &http.Transport{ var grafanaComProxyTransport = &http.Transport{
@ -41,7 +42,7 @@ func ReverseProxyGnetReq(proxyPath string) *httputil.ReverseProxy {
} }
func ProxyGnetRequest(c *models.ReqContext) { func ProxyGnetRequest(c *models.ReqContext) {
proxyPath := c.Params("*") proxyPath := macaron.Params(c.Req)["*"]
proxy := ReverseProxyGnetReq(proxyPath) proxy := ReverseProxyGnetReq(proxyPath)
proxy.Transport = grafanaComProxyTransport proxy.Transport = grafanaComProxyTransport
proxy.ServeHTTP(c.Resp, c.Req) proxy.ServeHTTP(c.Resp, c.Req)

@ -13,6 +13,7 @@ import (
"github.com/grafana/grafana/pkg/services/ldap" "github.com/grafana/grafana/pkg/services/ldap"
"github.com/grafana/grafana/pkg/services/multildap" "github.com/grafana/grafana/pkg/services/multildap"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
macaron "gopkg.in/macaron.v1"
) )
var ( var (
@ -238,7 +239,7 @@ func (hs *HTTPServer) GetUserFromLDAP(c *models.ReqContext) response.Response {
ldap := newLDAP(ldapConfig.Servers) ldap := newLDAP(ldapConfig.Servers)
username := c.Params(":username") username := macaron.Params(c.Req)[":username"]
if len(username) == 0 { if len(username) == 0 {
return response.Error(http.StatusBadRequest, "Validation error. You must specify an username", nil) return response.Error(http.StatusBadRequest, "Validation error. You must specify an username", nil)

@ -12,6 +12,7 @@ import (
"net/url" "net/url"
"golang.org/x/oauth2" "golang.org/x/oauth2"
macaron "gopkg.in/macaron.v1"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
@ -41,7 +42,7 @@ func (hs *HTTPServer) OAuthLogin(ctx *models.ReqContext) {
loginInfo := models.LoginInfo{ loginInfo := models.LoginInfo{
AuthModule: "oauth", AuthModule: "oauth",
} }
name := ctx.Params(":name") name := macaron.Params(ctx.Req)[":name"]
loginInfo.AuthModule = name loginInfo.AuthModule = name
provider := hs.SocialService.GetOAuthInfoProvider(name) provider := hs.SocialService.GetOAuthInfoProvider(name)
if provider == nil { if provider == nil {

@ -10,6 +10,7 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
macaron "gopkg.in/macaron.v1"
) )
// GET /api/org // GET /api/org
@ -24,7 +25,7 @@ func GetOrgByID(c *models.ReqContext) response.Response {
// Get /api/orgs/name/:name // Get /api/orgs/name/:name
func (hs *HTTPServer) GetOrgByName(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetOrgByName(c *models.ReqContext) response.Response {
org, err := hs.SQLStore.GetOrgByName(c.Params(":name")) org, err := hs.SQLStore.GetOrgByName(macaron.Params(c.Req)[":name"])
if err != nil { if err != nil {
if errors.Is(err, models.ErrOrgNotFound) { if errors.Is(err, models.ErrOrgNotFound) {
return response.Error(404, "Organization not found", err) return response.Error(404, "Organization not found", err)

@ -12,6 +12,7 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
macaron "gopkg.in/macaron.v1"
) )
func GetPendingOrgInvites(c *models.ReqContext) response.Response { func GetPendingOrgInvites(c *models.ReqContext) response.Response {
@ -131,7 +132,7 @@ func inviteExistingUserToOrg(c *models.ReqContext, user *models.User, inviteDto
} }
func RevokeInvite(c *models.ReqContext) response.Response { func RevokeInvite(c *models.ReqContext) response.Response {
if ok, rsp := updateTempUserStatus(c.Params(":code"), models.TmpUserRevoked); !ok { if ok, rsp := updateTempUserStatus(macaron.Params(c.Req)[":code"], models.TmpUserRevoked); !ok {
return rsp return rsp
} }
@ -142,7 +143,7 @@ func RevokeInvite(c *models.ReqContext) response.Response {
// A response containing an InviteInfo object is returned if the invite is found. // A response containing an InviteInfo object is returned if the invite is found.
// If a (pending) invite is not found, 404 is returned. // If a (pending) invite is not found, 404 is returned.
func GetInviteInfoByCode(c *models.ReqContext) response.Response { func GetInviteInfoByCode(c *models.ReqContext) response.Response {
query := models.GetTempUserByCodeQuery{Code: c.Params(":code")} query := models.GetTempUserByCodeQuery{Code: macaron.Params(c.Req)[":code"]}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
if errors.Is(err, models.ErrTempUserNotFound) { if errors.Is(err, models.ErrTempUserNotFound) {
return response.Error(404, "Invite not found", nil) return response.Error(404, "Invite not found", nil)

@ -17,6 +17,7 @@ import (
"github.com/grafana/grafana/pkg/plugins/backendplugin" "github.com/grafana/grafana/pkg/plugins/backendplugin"
"github.com/grafana/grafana/pkg/plugins/manager/installer" "github.com/grafana/grafana/pkg/plugins/manager/installer"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
macaron "gopkg.in/macaron.v1"
) )
func (hs *HTTPServer) GetPluginList(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetPluginList(c *models.ReqContext) response.Response {
@ -100,7 +101,7 @@ func (hs *HTTPServer) GetPluginList(c *models.ReqContext) response.Response {
} }
func (hs *HTTPServer) GetPluginSettingByID(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetPluginSettingByID(c *models.ReqContext) response.Response {
pluginID := c.Params(":pluginId") pluginID := macaron.Params(c.Req)[":pluginId"]
def := hs.PluginManager.GetPlugin(pluginID) def := hs.PluginManager.GetPlugin(pluginID)
if def == nil { if def == nil {
@ -145,7 +146,7 @@ func (hs *HTTPServer) GetPluginSettingByID(c *models.ReqContext) response.Respon
} }
func (hs *HTTPServer) UpdatePluginSetting(c *models.ReqContext, cmd models.UpdatePluginSettingCmd) response.Response { func (hs *HTTPServer) UpdatePluginSetting(c *models.ReqContext, cmd models.UpdatePluginSettingCmd) response.Response {
pluginID := c.Params(":pluginId") pluginID := macaron.Params(c.Req)[":pluginId"]
if app := hs.PluginManager.GetApp(pluginID); app == nil { if app := hs.PluginManager.GetApp(pluginID); app == nil {
return response.Error(404, "Plugin not installed", nil) return response.Error(404, "Plugin not installed", nil)
@ -161,7 +162,7 @@ func (hs *HTTPServer) UpdatePluginSetting(c *models.ReqContext, cmd models.Updat
} }
func (hs *HTTPServer) GetPluginDashboards(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetPluginDashboards(c *models.ReqContext) response.Response {
pluginID := c.Params(":pluginId") pluginID := macaron.Params(c.Req)[":pluginId"]
list, err := hs.PluginManager.GetPluginDashboards(c.OrgId, pluginID) list, err := hs.PluginManager.GetPluginDashboards(c.OrgId, pluginID)
if err != nil { if err != nil {
@ -177,8 +178,8 @@ func (hs *HTTPServer) GetPluginDashboards(c *models.ReqContext) response.Respons
} }
func (hs *HTTPServer) GetPluginMarkdown(c *models.ReqContext) response.Response { func (hs *HTTPServer) GetPluginMarkdown(c *models.ReqContext) response.Response {
pluginID := c.Params(":pluginId") pluginID := macaron.Params(c.Req)[":pluginId"]
name := c.Params(":name") name := macaron.Params(c.Req)[":name"]
content, err := hs.PluginManager.GetPluginMarkdown(pluginID, name) content, err := hs.PluginManager.GetPluginMarkdown(pluginID, name)
if err != nil { if err != nil {
@ -235,7 +236,7 @@ func (hs *HTTPServer) ImportDashboard(c *models.ReqContext, apiCmd dtos.ImportDa
// //
// /api/plugins/:pluginId/metrics // /api/plugins/:pluginId/metrics
func (hs *HTTPServer) CollectPluginMetrics(c *models.ReqContext) response.Response { func (hs *HTTPServer) CollectPluginMetrics(c *models.ReqContext) response.Response {
pluginID := c.Params("pluginId") pluginID := macaron.Params(c.Req)[":pluginId"]
plugin := hs.PluginManager.GetPlugin(pluginID) plugin := hs.PluginManager.GetPlugin(pluginID)
if plugin == nil { if plugin == nil {
return response.Error(404, "Plugin not found", nil) return response.Error(404, "Plugin not found", nil)
@ -256,14 +257,14 @@ func (hs *HTTPServer) CollectPluginMetrics(c *models.ReqContext) response.Respon
// //
// /public/plugins/:pluginId/* // /public/plugins/:pluginId/*
func (hs *HTTPServer) getPluginAssets(c *models.ReqContext) { func (hs *HTTPServer) getPluginAssets(c *models.ReqContext) {
pluginID := c.Params("pluginId") pluginID := macaron.Params(c.Req)[":pluginId"]
plugin := hs.PluginManager.GetPlugin(pluginID) plugin := hs.PluginManager.GetPlugin(pluginID)
if plugin == nil { if plugin == nil {
c.JsonApiErr(404, "Plugin not found", nil) c.JsonApiErr(404, "Plugin not found", nil)
return return
} }
requestedFile := filepath.Clean(c.Params("*")) requestedFile := filepath.Clean(macaron.Params(c.Req)["*"])
pluginFilePath := filepath.Join(plugin.PluginDir, requestedFile) pluginFilePath := filepath.Join(plugin.PluginDir, requestedFile)
if !plugin.IncludedInSignature(requestedFile) { if !plugin.IncludedInSignature(requestedFile) {
@ -307,7 +308,7 @@ func (hs *HTTPServer) getPluginAssets(c *models.ReqContext) {
// CheckHealth returns the health of a plugin. // CheckHealth returns the health of a plugin.
// /api/plugins/:pluginId/health // /api/plugins/:pluginId/health
func (hs *HTTPServer) CheckHealth(c *models.ReqContext) response.Response { func (hs *HTTPServer) CheckHealth(c *models.ReqContext) response.Response {
pluginID := c.Params("pluginId") pluginID := macaron.Params(c.Req)[":pluginId"]
pCtx, found, err := hs.PluginContextProvider.Get(pluginID, "", c.SignedInUser, false) pCtx, found, err := hs.PluginContextProvider.Get(pluginID, "", c.SignedInUser, false)
if err != nil { if err != nil {
@ -349,7 +350,7 @@ func (hs *HTTPServer) CheckHealth(c *models.ReqContext) response.Response {
// //
// /api/plugins/:pluginId/resources/* // /api/plugins/:pluginId/resources/*
func (hs *HTTPServer) CallResource(c *models.ReqContext) { func (hs *HTTPServer) CallResource(c *models.ReqContext) {
pluginID := c.Params("pluginId") pluginID := macaron.Params(c.Req)[":pluginId"]
pCtx, found, err := hs.PluginContextProvider.Get(pluginID, "", c.SignedInUser, false) pCtx, found, err := hs.PluginContextProvider.Get(pluginID, "", c.SignedInUser, false)
if err != nil { if err != nil {
@ -360,7 +361,7 @@ func (hs *HTTPServer) CallResource(c *models.ReqContext) {
c.JsonApiErr(404, "Plugin not found", nil) c.JsonApiErr(404, "Plugin not found", nil)
return return
} }
hs.BackendPluginManager.CallResource(pCtx, c, c.Params("*")) hs.BackendPluginManager.CallResource(pCtx, c, macaron.Params(c.Req)["*"])
} }
func (hs *HTTPServer) GetPluginErrorsList(_ *models.ReqContext) response.Response { func (hs *HTTPServer) GetPluginErrorsList(_ *models.ReqContext) response.Response {
@ -368,7 +369,7 @@ func (hs *HTTPServer) GetPluginErrorsList(_ *models.ReqContext) response.Respons
} }
func (hs *HTTPServer) InstallPlugin(c *models.ReqContext, dto dtos.InstallPluginCommand) response.Response { func (hs *HTTPServer) InstallPlugin(c *models.ReqContext, dto dtos.InstallPluginCommand) response.Response {
pluginID := c.Params("pluginId") pluginID := macaron.Params(c.Req)[":pluginId"]
err := hs.PluginManager.Install(c.Req.Context(), pluginID, dto.Version) err := hs.PluginManager.Install(c.Req.Context(), pluginID, dto.Version)
if err != nil { if err != nil {
@ -399,7 +400,7 @@ func (hs *HTTPServer) InstallPlugin(c *models.ReqContext, dto dtos.InstallPlugin
} }
func (hs *HTTPServer) UninstallPlugin(c *models.ReqContext) response.Response { func (hs *HTTPServer) UninstallPlugin(c *models.ReqContext) response.Response {
pluginID := c.Params("pluginId") pluginID := macaron.Params(c.Req)[":pluginId"]
err := hs.PluginManager.Uninstall(c.Req.Context(), pluginID) err := hs.PluginManager.Uninstall(c.Req.Context(), pluginID)
if err != nil { if err != nil {

@ -5,6 +5,7 @@ import (
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
macaron "gopkg.in/macaron.v1"
) )
func GetOrgQuotas(c *models.ReqContext) response.Response { func GetOrgQuotas(c *models.ReqContext) response.Response {
@ -25,7 +26,7 @@ func UpdateOrgQuota(c *models.ReqContext, cmd models.UpdateOrgQuotaCmd) response
return response.Error(404, "Quotas not enabled", nil) return response.Error(404, "Quotas not enabled", nil)
} }
cmd.OrgId = c.ParamsInt64(":orgId") cmd.OrgId = c.ParamsInt64(":orgId")
cmd.Target = c.Params(":target") cmd.Target = macaron.Params(c.Req)[":target"]
if _, ok := setting.Quota.Org.ToMap()[cmd.Target]; !ok { if _, ok := setting.Quota.Org.ToMap()[cmd.Target]; !ok {
return response.Error(404, "Invalid quota target", nil) return response.Error(404, "Invalid quota target", nil)
@ -55,7 +56,7 @@ func UpdateUserQuota(c *models.ReqContext, cmd models.UpdateUserQuotaCmd) respon
return response.Error(404, "Quotas not enabled", nil) return response.Error(404, "Quotas not enabled", nil)
} }
cmd.UserId = c.ParamsInt64(":id") cmd.UserId = c.ParamsInt64(":id")
cmd.Target = c.Params(":target") cmd.Target = macaron.Params(c.Req)[":target"]
if _, ok := setting.Quota.User.ToMap()[cmd.Target]; !ok { if _, ok := setting.Quota.User.ToMap()[cmd.Target]; !ok {
return response.Error(404, "Invalid quota target", nil) return response.Error(404, "Invalid quota target", nil)

@ -10,6 +10,7 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/rendering" "github.com/grafana/grafana/pkg/services/rendering"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
macaron "gopkg.in/macaron.v1"
) )
func (hs *HTTPServer) RenderToPng(c *models.ReqContext) { func (hs *HTTPServer) RenderToPng(c *models.ReqContext) {
@ -58,7 +59,7 @@ func (hs *HTTPServer) RenderToPng(c *models.ReqContext) {
OrgID: c.OrgId, OrgID: c.OrgId,
UserID: c.UserId, UserID: c.UserId,
OrgRole: c.OrgRole, OrgRole: c.OrgRole,
Path: c.Params("*") + queryParams, Path: macaron.Params(c.Req)["*"] + queryParams,
Timezone: queryReader.Get("tz", ""), Timezone: queryReader.Get("tz", ""),
Encoding: queryReader.Get("encoding", ""), Encoding: queryReader.Get("encoding", ""),
ConcurrentLimit: hs.Cfg.RendererConcurrentRequestLimit, ConcurrentLimit: hs.Cfg.RendererConcurrentRequestLimit,

@ -11,6 +11,7 @@ import (
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
macaron "gopkg.in/macaron.v1"
) )
// createShortURL handles requests to create short URLs. // createShortURL handles requests to create short URLs.
@ -45,7 +46,7 @@ func (hs *HTTPServer) createShortURL(c *models.ReqContext, cmd dtos.CreateShortU
} }
func (hs *HTTPServer) redirectFromShortURL(c *models.ReqContext) { func (hs *HTTPServer) redirectFromShortURL(c *models.ReqContext) {
shortURLUID := c.Params(":uid") shortURLUID := macaron.Params(c.Req)[":uid"]
if !util.IsValidShortUID(shortURLUID) { if !util.IsValidShortUID(shortURLUID) {
return return

@ -219,7 +219,7 @@ func URL(obj interface{}, ifacePtr ...interface{}) macaron.Handler {
obj := reflect.New(reflect.TypeOf(obj)) obj := reflect.New(reflect.TypeOf(obj))
val := obj.Elem() val := obj.Elem()
for k, v := range ctx.AllParams() { for k, v := range macaron.Params(ctx.Req) {
field := val.FieldByName(k[1:]) field := val.FieldByName(k[1:])
if field.IsValid() { if field.IsValid() {
errors = setWithProperType(field.Kind(), v, field, k, errors) errors = setWithProperType(field.Kind(), v, field, k, errors)

@ -43,7 +43,6 @@ type Context struct {
*Router *Router
Req *http.Request Req *http.Request
Resp ResponseWriter Resp ResponseWriter
params Params
template *template.Template template *template.Template
} }
@ -180,32 +179,10 @@ func (ctx *Context) QueryInt64(name string) int64 {
return n return n
} }
// Params returns value of given param name.
// e.g. ctx.Params(":uid") or ctx.Params("uid")
func (ctx *Context) Params(name string) string {
if len(name) == 0 {
return ""
}
if len(name) > 1 && name[0] != ':' {
name = ":" + name
}
return ctx.params[name]
}
// AllParams returns all params.
func (ctx *Context) AllParams() Params {
return ctx.params
}
// ReplaceAllParams replace all current params with given params
func (ctx *Context) ReplaceAllParams(params Params) {
ctx.params = params
}
// ParamsInt64 returns params result in int64 type. // ParamsInt64 returns params result in int64 type.
// e.g. ctx.ParamsInt64(":uid") // e.g. ctx.ParamsInt64(":uid")
func (ctx *Context) ParamsInt64(name string) int64 { func (ctx *Context) ParamsInt64(name string) int64 {
n, _ := strconv.ParseInt(ctx.Params(name), 10, 64) n, _ := strconv.ParseInt(Params(ctx.Req)[name], 10, 64)
return n return n
} }

@ -130,7 +130,7 @@ func (inj *injector) fastInvoke(f FastInvoker, t reflect.Type, numIn int) ([]ref
argType = t.In(i) argType = t.In(i)
val = inj.GetVal(argType) val = inj.GetVal(argType)
if !val.IsValid() { if !val.IsValid() {
return nil, fmt.Errorf("Value not found for type %v", argType) return nil, fmt.Errorf("value not found for type %v", argType)
} }
in[i] = val.Interface() in[i] = val.Interface()
@ -150,7 +150,7 @@ func (inj *injector) callInvoke(f interface{}, t reflect.Type, numIn int) ([]ref
argType = t.In(i) argType = t.In(i)
val = inj.GetVal(argType) val = inj.GetVal(argType)
if !val.IsValid() { if !val.IsValid() {
return nil, fmt.Errorf("Value not found for type %v", argType) return nil, fmt.Errorf("value not found for type %v", argType)
} }
in[i] = val in[i] = val

@ -118,6 +118,21 @@ func FromContext(c context.Context) *Context {
return nil return nil
} }
type paramsKey struct{}
// Params returns the named route parameters for the current request, if any.
func Params(r *http.Request) map[string]string {
if rv := r.Context().Value(paramsKey{}); rv != nil {
return rv.(map[string]string)
}
return map[string]string{}
}
// SetURLParams sets the named URL parameters for the given request. This should only be used for testing purposes.
func SetURLParams(r *http.Request, vars map[string]string) *http.Request {
return r.WithContext(context.WithValue(r.Context(), paramsKey{}, vars))
}
// UseMiddleware is a traditional approach to writing middleware in Go. // UseMiddleware is a traditional approach to writing middleware in Go.
// A middleware is a function that has a reference to the next handler in the chain // A middleware is a function that has a reference to the next handler in the chain
// and returns the actual middleware handler, that may do its job and optionally // and returns the actual middleware handler, that may do its job and optionally

@ -90,11 +90,9 @@ func NewRouter() *Router {
} }
} }
type Params map[string]string
// Handle is a function that can be registered to a route to handle HTTP requests. // Handle is a function that can be registered to a route to handle HTTP requests.
// Like http.HandlerFunc, but has a third parameter for the values of wildcards (variables). // Like http.HandlerFunc, but has a third parameter for the values of wildcards (variables).
type Handle func(http.ResponseWriter, *http.Request, Params) type Handle func(http.ResponseWriter, *http.Request, map[string]string)
// handle adds new route to the router tree. // handle adds new route to the router tree.
func (r *Router) handle(method, pattern string, handle Handle) { func (r *Router) handle(method, pattern string, handle Handle) {
@ -150,9 +148,8 @@ func (r *Router) Handle(method string, pattern string, handlers []Handler) {
} }
handlers = validateAndWrapHandlers(handlers) handlers = validateAndWrapHandlers(handlers)
r.handle(method, pattern, func(resp http.ResponseWriter, req *http.Request, params Params) { r.handle(method, pattern, func(resp http.ResponseWriter, req *http.Request, params map[string]string) {
c := r.m.createContext(resp, req) c := r.m.createContext(resp, SetURLParams(req, params))
c.params = params
c.handlers = make([]Handler, 0, len(r.m.handlers)+len(handlers)) c.handlers = make([]Handler, 0, len(r.m.handlers)+len(handlers))
c.handlers = append(c.handlers, r.m.handlers...) c.handlers = append(c.handlers, r.m.handlers...)
c.handlers = append(c.handlers, handlers...) c.handlers = append(c.handlers, handlers...)

@ -260,7 +260,7 @@ func (t *Tree) Add(pattern string, handle Handle) *Leaf {
return t.addNextSegment(pattern, handle) return t.addNextSegment(pattern, handle)
} }
func (t *Tree) matchLeaf(globLevel int, url string, params Params) (Handle, bool) { func (t *Tree) matchLeaf(globLevel int, url string, params map[string]string) (Handle, bool) {
url, err := urlpkg.PathUnescape(url) url, err := urlpkg.PathUnescape(url)
if err != nil { if err != nil {
return nil, false return nil, false
@ -303,7 +303,7 @@ func (t *Tree) matchLeaf(globLevel int, url string, params Params) (Handle, bool
return nil, false return nil, false
} }
func (t *Tree) matchSubtree(globLevel int, segment, url string, params Params) (Handle, bool) { func (t *Tree) matchSubtree(globLevel int, segment, url string, params map[string]string) (Handle, bool) {
unescapedSegment, err := urlpkg.PathUnescape(segment) unescapedSegment, err := urlpkg.PathUnescape(segment)
if err != nil { if err != nil {
return nil, false return nil, false
@ -365,7 +365,7 @@ func (t *Tree) matchSubtree(globLevel int, segment, url string, params Params) (
return nil, false return nil, false
} }
func (t *Tree) matchNextSegment(globLevel int, url string, params Params) (Handle, bool) { func (t *Tree) matchNextSegment(globLevel int, url string, params map[string]string) (Handle, bool) {
i := strings.Index(url, "/") i := strings.Index(url, "/")
if i == -1 { if i == -1 {
return t.matchLeaf(globLevel, url, params) return t.matchLeaf(globLevel, url, params)
@ -373,10 +373,10 @@ func (t *Tree) matchNextSegment(globLevel int, url string, params Params) (Handl
return t.matchSubtree(globLevel, url[:i], url[i+1:], params) return t.matchSubtree(globLevel, url[:i], url[i+1:], params)
} }
func (t *Tree) Match(url string) (Handle, Params, bool) { func (t *Tree) Match(url string) (Handle, map[string]string, bool) {
url = strings.TrimPrefix(url, "/") url = strings.TrimPrefix(url, "/")
url = strings.TrimSuffix(url, "/") url = strings.TrimSuffix(url, "/")
params := make(Params) params := map[string]string{}
handle, ok := t.matchNextSegment(0, url, params) handle, ok := t.matchNextSegment(0, url, params)
return handle, params, ok return handle, params, ok
} }

@ -8,13 +8,14 @@ package pluginextensionv2
import ( import (
context "context" context "context"
reflect "reflect"
sync "sync"
grpc "google.golang.org/grpc" grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes" codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status" status "google.golang.org/grpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl" protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
) )
const ( const (

@ -19,7 +19,7 @@ func Middleware(ac accesscontrol.AccessControl) func(macaron.Handler, accesscont
} }
return func(c *models.ReqContext) { return func(c *models.ReqContext) {
injected, err := evaluator.Inject(c.AllParams()) injected, err := evaluator.Inject(macaron.Params(c.Req))
if err != nil { if err != nil {
c.JsonApiErr(http.StatusInternalServerError, "Internal server error", err) c.JsonApiErr(http.StatusInternalServerError, "Internal server error", err)
return return

@ -4,6 +4,7 @@ import (
"errors" "errors"
"github.com/go-macaron/binding" "github.com/go-macaron/binding"
"gopkg.in/macaron.v1"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
"github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/api/routing"
@ -35,7 +36,7 @@ func (l *LibraryElementService) createHandler(c *models.ReqContext, cmd CreateLi
// deleteHandler handles DELETE /api/library-elements/:uid. // deleteHandler handles DELETE /api/library-elements/:uid.
func (l *LibraryElementService) deleteHandler(c *models.ReqContext) response.Response { func (l *LibraryElementService) deleteHandler(c *models.ReqContext) response.Response {
err := l.deleteLibraryElement(c, c.Params(":uid")) err := l.deleteLibraryElement(c, macaron.Params(c.Req)[":uid"])
if err != nil { if err != nil {
return toLibraryElementError(err, "Failed to delete library element") return toLibraryElementError(err, "Failed to delete library element")
} }
@ -75,7 +76,7 @@ func (l *LibraryElementService) getAllHandler(c *models.ReqContext) response.Res
// patchHandler handles PATCH /api/library-elements/:uid // patchHandler handles PATCH /api/library-elements/:uid
func (l *LibraryElementService) patchHandler(c *models.ReqContext, cmd patchLibraryElementCommand) response.Response { func (l *LibraryElementService) patchHandler(c *models.ReqContext, cmd patchLibraryElementCommand) response.Response {
element, err := l.patchLibraryElement(c, cmd, c.Params(":uid")) element, err := l.patchLibraryElement(c, cmd, macaron.Params(c.Req)[":uid"])
if err != nil { if err != nil {
return toLibraryElementError(err, "Failed to update library element") return toLibraryElementError(err, "Failed to update library element")
} }
@ -85,7 +86,7 @@ func (l *LibraryElementService) patchHandler(c *models.ReqContext, cmd patchLibr
// getConnectionsHandler handles GET /api/library-panels/:uid/connections/. // getConnectionsHandler handles GET /api/library-panels/:uid/connections/.
func (l *LibraryElementService) getConnectionsHandler(c *models.ReqContext) response.Response { func (l *LibraryElementService) getConnectionsHandler(c *models.ReqContext) response.Response {
connections, err := l.getConnections(c, c.Params(":uid")) connections, err := l.getConnections(c, macaron.Params(c.Req)[":uid"])
if err != nil { if err != nil {
return toLibraryElementError(err, "Failed to get connections") return toLibraryElementError(err, "Failed to get connections")
} }

@ -14,6 +14,7 @@ import (
"github.com/grafana/grafana/pkg/services/sqlstore" "github.com/grafana/grafana/pkg/services/sqlstore"
"github.com/grafana/grafana/pkg/services/sqlstore/migrator" "github.com/grafana/grafana/pkg/services/sqlstore/migrator"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
"gopkg.in/macaron.v1"
) )
const ( const (
@ -274,7 +275,7 @@ func (l *LibraryElementService) getLibraryElements(c *models.ReqContext, params
// getLibraryElementByUid gets a Library Element by uid. // getLibraryElementByUid gets a Library Element by uid.
func (l *LibraryElementService) getLibraryElementByUid(c *models.ReqContext) (LibraryElementDTO, error) { func (l *LibraryElementService) getLibraryElementByUid(c *models.ReqContext) (LibraryElementDTO, error) {
libraryElements, err := l.getLibraryElements(c, []Pair{{key: "org_id", value: c.SignedInUser.OrgId}, {key: "uid", value: c.Params(":uid")}}) libraryElements, err := l.getLibraryElements(c, []Pair{{key: "org_id", value: c.SignedInUser.OrgId}, {key: "uid", value: macaron.Params(c.Req)[":uid"]}})
if err != nil { if err != nil {
return LibraryElementDTO{}, err return LibraryElementDTO{}, err
} }
@ -287,7 +288,7 @@ func (l *LibraryElementService) getLibraryElementByUid(c *models.ReqContext) (Li
// getLibraryElementByName gets a Library Element by name. // getLibraryElementByName gets a Library Element by name.
func (l *LibraryElementService) getLibraryElementsByName(c *models.ReqContext) ([]LibraryElementDTO, error) { func (l *LibraryElementService) getLibraryElementsByName(c *models.ReqContext) ([]LibraryElementDTO, error) {
return l.getLibraryElements(c, []Pair{{"org_id", c.SignedInUser.OrgId}, {"name", c.Params(":name")}}) return l.getLibraryElements(c, []Pair{{"org_id", c.SignedInUser.OrgId}, {"name", macaron.Params(c.Req)[":name"]}})
} }
// getAllLibraryElements gets all Library Elements. // getAllLibraryElements gets all Library Elements.

@ -4,6 +4,7 @@ import (
"testing" "testing"
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"gopkg.in/macaron.v1"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -19,14 +20,14 @@ func TestDeleteLibraryElement(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to delete a library panel that exists, it should succeed", scenarioWithPanel(t, "When an admin tries to delete a library panel that exists, it should succeed",
func(t *testing.T, sc scenarioContext) { func(t *testing.T, sc scenarioContext) {
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.deleteHandler(sc.reqContext) resp := sc.service.deleteHandler(sc.reqContext)
require.Equal(t, 200, resp.Status()) require.Equal(t, 200, resp.Status())
}) })
scenarioWithPanel(t, "When an admin tries to delete a library panel in another org, it should fail", scenarioWithPanel(t, "When an admin tries to delete a library panel in another org, it should fail",
func(t *testing.T, sc scenarioContext) { func(t *testing.T, sc scenarioContext) {
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
sc.reqContext.SignedInUser.OrgId = 2 sc.reqContext.SignedInUser.OrgId = 2
sc.reqContext.SignedInUser.OrgRole = models.ROLE_ADMIN sc.reqContext.SignedInUser.OrgRole = models.ROLE_ADMIN
resp := sc.service.deleteHandler(sc.reqContext) resp := sc.service.deleteHandler(sc.reqContext)
@ -69,7 +70,7 @@ func TestDeleteLibraryElement(t *testing.T) {
err := sc.service.ConnectElementsToDashboard(sc.reqContext, []string{sc.initialResult.Result.UID}, dashInDB.Id) err := sc.service.ConnectElementsToDashboard(sc.reqContext, []string{sc.initialResult.Result.UID}, dashInDB.Id)
require.NoError(t, err) require.NoError(t, err)
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.deleteHandler(sc.reqContext) resp := sc.service.deleteHandler(sc.reqContext)
require.Equal(t, 403, resp.Status()) require.Equal(t, 403, resp.Status())
}) })

@ -4,6 +4,7 @@ import (
"testing" "testing"
"github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/components/simplejson"
"gopkg.in/macaron.v1"
"github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -15,12 +16,12 @@ func TestGetLibraryElement(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to get a library panel that does not exist, it should fail", scenarioWithPanel(t, "When an admin tries to get a library panel that does not exist, it should fail",
func(t *testing.T, sc scenarioContext) { func(t *testing.T, sc scenarioContext) {
// by uid // by uid
sc.reqContext.ReplaceAllParams(map[string]string{":uid": "unknown"}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": "unknown"})
resp := sc.service.getHandler(sc.reqContext) resp := sc.service.getHandler(sc.reqContext)
require.Equal(t, 404, resp.Status()) require.Equal(t, 404, resp.Status())
// by name // by name
sc.reqContext.ReplaceAllParams(map[string]string{":name": "unknown"}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":name": "unknown"})
resp = sc.service.getByNameHandler(sc.reqContext) resp = sc.service.getByNameHandler(sc.reqContext)
require.Equal(t, 404, resp.Status()) require.Equal(t, 404, resp.Status())
}) })
@ -68,7 +69,7 @@ func TestGetLibraryElement(t *testing.T) {
} }
// by uid // by uid
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.getHandler(sc.reqContext) resp := sc.service.getHandler(sc.reqContext)
var result = validateAndUnMarshalResponse(t, resp) var result = validateAndUnMarshalResponse(t, resp)
@ -77,7 +78,7 @@ func TestGetLibraryElement(t *testing.T) {
} }
// by name // by name
sc.reqContext.ReplaceAllParams(map[string]string{":name": sc.initialResult.Result.Name}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":name": sc.initialResult.Result.Name})
resp = sc.service.getByNameHandler(sc.reqContext) resp = sc.service.getByNameHandler(sc.reqContext)
arrayResult := validateAndUnMarshalArrayResponse(t, resp) arrayResult := validateAndUnMarshalArrayResponse(t, resp)
@ -163,7 +164,7 @@ func TestGetLibraryElement(t *testing.T) {
} }
// by uid // by uid
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.getHandler(sc.reqContext) resp := sc.service.getHandler(sc.reqContext)
result := validateAndUnMarshalResponse(t, resp) result := validateAndUnMarshalResponse(t, resp)
@ -172,7 +173,7 @@ func TestGetLibraryElement(t *testing.T) {
} }
// by name // by name
sc.reqContext.ReplaceAllParams(map[string]string{":name": sc.initialResult.Result.Name}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":name": sc.initialResult.Result.Name})
resp = sc.service.getByNameHandler(sc.reqContext) resp = sc.service.getByNameHandler(sc.reqContext)
arrayResult := validateAndUnMarshalArrayResponse(t, resp) arrayResult := validateAndUnMarshalArrayResponse(t, resp)
if diff := cmp.Diff(libraryElementArrayResult{Result: []libraryElement{expected(result).Result}}, arrayResult, getCompareOptions()...); diff != "" { if diff := cmp.Diff(libraryElementArrayResult{Result: []libraryElement{expected(result).Result}}, arrayResult, getCompareOptions()...); diff != "" {
@ -186,12 +187,12 @@ func TestGetLibraryElement(t *testing.T) {
sc.reqContext.SignedInUser.OrgRole = models.ROLE_ADMIN sc.reqContext.SignedInUser.OrgRole = models.ROLE_ADMIN
// by uid // by uid
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.getHandler(sc.reqContext) resp := sc.service.getHandler(sc.reqContext)
require.Equal(t, 404, resp.Status()) require.Equal(t, 404, resp.Status())
// by name // by name
sc.reqContext.ReplaceAllParams(map[string]string{":name": sc.initialResult.Result.Name}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":name": sc.initialResult.Result.Name})
resp = sc.service.getByNameHandler(sc.reqContext) resp = sc.service.getByNameHandler(sc.reqContext)
require.Equal(t, 404, resp.Status()) require.Equal(t, 404, resp.Status())
}) })

@ -7,6 +7,7 @@ import (
"github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"gopkg.in/macaron.v1"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
) )
@ -15,7 +16,7 @@ func TestPatchLibraryElement(t *testing.T) {
scenarioWithPanel(t, "When an admin tries to patch a library panel that does not exist, it should fail", scenarioWithPanel(t, "When an admin tries to patch a library panel that does not exist, it should fail",
func(t *testing.T, sc scenarioContext) { func(t *testing.T, sc scenarioContext) {
cmd := patchLibraryElementCommand{Kind: int64(models.PanelElement)} cmd := patchLibraryElementCommand{Kind: int64(models.PanelElement)}
sc.reqContext.ReplaceAllParams(map[string]string{":uid": "unknown"}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": "unknown"})
resp := sc.service.patchHandler(sc.reqContext, cmd) resp := sc.service.patchHandler(sc.reqContext, cmd)
require.Equal(t, 404, resp.Status()) require.Equal(t, 404, resp.Status())
}) })
@ -38,7 +39,7 @@ func TestPatchLibraryElement(t *testing.T) {
Kind: int64(models.PanelElement), Kind: int64(models.PanelElement),
Version: 1, Version: 1,
} }
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.patchHandler(sc.reqContext, cmd) resp := sc.service.patchHandler(sc.reqContext, cmd)
require.Equal(t, 200, resp.Status()) require.Equal(t, 200, resp.Status())
var result = validateAndUnMarshalResponse(t, resp) var result = validateAndUnMarshalResponse(t, resp)
@ -90,7 +91,7 @@ func TestPatchLibraryElement(t *testing.T) {
Kind: int64(models.PanelElement), Kind: int64(models.PanelElement),
Version: 1, Version: 1,
} }
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.patchHandler(sc.reqContext, cmd) resp := sc.service.patchHandler(sc.reqContext, cmd)
require.Equal(t, 200, resp.Status()) require.Equal(t, 200, resp.Status())
var result = validateAndUnMarshalResponse(t, resp) var result = validateAndUnMarshalResponse(t, resp)
@ -111,7 +112,7 @@ func TestPatchLibraryElement(t *testing.T) {
Kind: int64(models.PanelElement), Kind: int64(models.PanelElement),
Version: 1, Version: 1,
} }
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.patchHandler(sc.reqContext, cmd) resp := sc.service.patchHandler(sc.reqContext, cmd)
var result = validateAndUnMarshalResponse(t, resp) var result = validateAndUnMarshalResponse(t, resp)
sc.initialResult.Result.Name = "New Name" sc.initialResult.Result.Name = "New Name"
@ -132,7 +133,7 @@ func TestPatchLibraryElement(t *testing.T) {
Kind: int64(models.PanelElement), Kind: int64(models.PanelElement),
Version: 1, Version: 1,
} }
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.patchHandler(sc.reqContext, cmd) resp := sc.service.patchHandler(sc.reqContext, cmd)
var result = validateAndUnMarshalResponse(t, resp) var result = validateAndUnMarshalResponse(t, resp)
sc.initialResult.Result.UID = cmd.UID sc.initialResult.Result.UID = cmd.UID
@ -153,7 +154,7 @@ func TestPatchLibraryElement(t *testing.T) {
Kind: int64(models.PanelElement), Kind: int64(models.PanelElement),
Version: 1, Version: 1,
} }
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.patchHandler(sc.reqContext, cmd) resp := sc.service.patchHandler(sc.reqContext, cmd)
require.Equal(t, 400, resp.Status()) require.Equal(t, 400, resp.Status())
}) })
@ -166,7 +167,7 @@ func TestPatchLibraryElement(t *testing.T) {
Kind: int64(models.PanelElement), Kind: int64(models.PanelElement),
Version: 1, Version: 1,
} }
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.patchHandler(sc.reqContext, cmd) resp := sc.service.patchHandler(sc.reqContext, cmd)
require.Equal(t, 400, resp.Status()) require.Equal(t, 400, resp.Status())
}) })
@ -183,7 +184,7 @@ func TestPatchLibraryElement(t *testing.T) {
Kind: int64(models.PanelElement), Kind: int64(models.PanelElement),
Version: 1, Version: 1,
} }
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp = sc.service.patchHandler(sc.reqContext, cmd) resp = sc.service.patchHandler(sc.reqContext, cmd)
require.Equal(t, 400, resp.Status()) require.Equal(t, 400, resp.Status())
}) })
@ -196,7 +197,7 @@ func TestPatchLibraryElement(t *testing.T) {
Kind: int64(models.PanelElement), Kind: int64(models.PanelElement),
Version: 1, Version: 1,
} }
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.patchHandler(sc.reqContext, cmd) resp := sc.service.patchHandler(sc.reqContext, cmd)
var result = validateAndUnMarshalResponse(t, resp) var result = validateAndUnMarshalResponse(t, resp)
sc.initialResult.Result.Type = "graph" sc.initialResult.Result.Type = "graph"
@ -223,7 +224,7 @@ func TestPatchLibraryElement(t *testing.T) {
Kind: int64(models.PanelElement), Kind: int64(models.PanelElement),
Version: 1, Version: 1,
} }
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.patchHandler(sc.reqContext, cmd) resp := sc.service.patchHandler(sc.reqContext, cmd)
var result = validateAndUnMarshalResponse(t, resp) var result = validateAndUnMarshalResponse(t, resp)
sc.initialResult.Result.Type = "text" sc.initialResult.Result.Type = "text"
@ -248,7 +249,7 @@ func TestPatchLibraryElement(t *testing.T) {
Kind: int64(models.PanelElement), Kind: int64(models.PanelElement),
Version: 1, Version: 1,
} }
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.patchHandler(sc.reqContext, cmd) resp := sc.service.patchHandler(sc.reqContext, cmd)
var result = validateAndUnMarshalResponse(t, resp) var result = validateAndUnMarshalResponse(t, resp)
sc.initialResult.Result.Type = "graph" sc.initialResult.Result.Type = "graph"
@ -269,7 +270,7 @@ func TestPatchLibraryElement(t *testing.T) {
func(t *testing.T, sc scenarioContext) { func(t *testing.T, sc scenarioContext) {
cmd := patchLibraryElementCommand{FolderID: -1, Version: 1, Kind: int64(models.PanelElement)} cmd := patchLibraryElementCommand{FolderID: -1, Version: 1, Kind: int64(models.PanelElement)}
sc.reqContext.UserId = 2 sc.reqContext.UserId = 2
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.patchHandler(sc.reqContext, cmd) resp := sc.service.patchHandler(sc.reqContext, cmd)
var result = validateAndUnMarshalResponse(t, resp) var result = validateAndUnMarshalResponse(t, resp)
sc.initialResult.Result.Meta.UpdatedBy.ID = int64(2) sc.initialResult.Result.Meta.UpdatedBy.ID = int64(2)
@ -291,7 +292,7 @@ func TestPatchLibraryElement(t *testing.T) {
Version: 1, Version: 1,
Kind: int64(models.PanelElement), Kind: int64(models.PanelElement),
} }
sc.reqContext.ReplaceAllParams(map[string]string{":uid": result.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.Result.UID})
resp = sc.service.patchHandler(sc.reqContext, cmd) resp = sc.service.patchHandler(sc.reqContext, cmd)
require.Equal(t, 400, resp.Status()) require.Equal(t, 400, resp.Status())
}) })
@ -307,7 +308,7 @@ func TestPatchLibraryElement(t *testing.T) {
Version: 1, Version: 1,
Kind: int64(models.PanelElement), Kind: int64(models.PanelElement),
} }
sc.reqContext.ReplaceAllParams(map[string]string{":uid": result.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.Result.UID})
resp = sc.service.patchHandler(sc.reqContext, cmd) resp = sc.service.patchHandler(sc.reqContext, cmd)
require.Equal(t, 400, resp.Status()) require.Equal(t, 400, resp.Status())
}) })
@ -320,7 +321,7 @@ func TestPatchLibraryElement(t *testing.T) {
Kind: int64(models.PanelElement), Kind: int64(models.PanelElement),
} }
sc.reqContext.OrgId = 2 sc.reqContext.OrgId = 2
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.patchHandler(sc.reqContext, cmd) resp := sc.service.patchHandler(sc.reqContext, cmd)
require.Equal(t, 404, resp.Status()) require.Equal(t, 404, resp.Status())
}) })
@ -332,7 +333,7 @@ func TestPatchLibraryElement(t *testing.T) {
Version: 1, Version: 1,
Kind: int64(models.PanelElement), Kind: int64(models.PanelElement),
} }
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.patchHandler(sc.reqContext, cmd) resp := sc.service.patchHandler(sc.reqContext, cmd)
require.Equal(t, 200, resp.Status()) require.Equal(t, 200, resp.Status())
resp = sc.service.patchHandler(sc.reqContext, cmd) resp = sc.service.patchHandler(sc.reqContext, cmd)
@ -346,7 +347,7 @@ func TestPatchLibraryElement(t *testing.T) {
Version: 1, Version: 1,
Kind: int64(models.VariableElement), Kind: int64(models.VariableElement),
} }
sc.reqContext.ReplaceAllParams(map[string]string{":uid": sc.initialResult.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": sc.initialResult.Result.UID})
resp := sc.service.patchHandler(sc.reqContext, cmd) resp := sc.service.patchHandler(sc.reqContext, cmd)
require.Equal(t, 200, resp.Status()) require.Equal(t, 200, resp.Status())
var result = validateAndUnMarshalResponse(t, resp) var result = validateAndUnMarshalResponse(t, resp)

@ -7,6 +7,7 @@ import (
"github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"gopkg.in/macaron.v1"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
) )
@ -85,7 +86,7 @@ func TestLibraryElementPermissions(t *testing.T) {
sc.reqContext.SignedInUser.OrgRole = testCase.role sc.reqContext.SignedInUser.OrgRole = testCase.role
cmd := patchLibraryElementCommand{FolderID: toFolder.Id, Version: 1, Kind: int64(models.PanelElement)} cmd := patchLibraryElementCommand{FolderID: toFolder.Id, Version: 1, Kind: int64(models.PanelElement)}
sc.reqContext.ReplaceAllParams(map[string]string{":uid": result.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.Result.UID})
resp = sc.service.patchHandler(sc.reqContext, cmd) resp = sc.service.patchHandler(sc.reqContext, cmd)
require.Equal(t, testCase.status, resp.Status()) require.Equal(t, testCase.status, resp.Status())
}) })
@ -100,7 +101,7 @@ func TestLibraryElementPermissions(t *testing.T) {
sc.reqContext.SignedInUser.OrgRole = testCase.role sc.reqContext.SignedInUser.OrgRole = testCase.role
cmd := patchLibraryElementCommand{FolderID: toFolder.Id, Version: 1, Kind: int64(models.PanelElement)} cmd := patchLibraryElementCommand{FolderID: toFolder.Id, Version: 1, Kind: int64(models.PanelElement)}
sc.reqContext.ReplaceAllParams(map[string]string{":uid": result.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.Result.UID})
resp = sc.service.patchHandler(sc.reqContext, cmd) resp = sc.service.patchHandler(sc.reqContext, cmd)
require.Equal(t, testCase.status, resp.Status()) require.Equal(t, testCase.status, resp.Status())
}) })
@ -113,7 +114,7 @@ func TestLibraryElementPermissions(t *testing.T) {
result := validateAndUnMarshalResponse(t, resp) result := validateAndUnMarshalResponse(t, resp)
sc.reqContext.SignedInUser.OrgRole = testCase.role sc.reqContext.SignedInUser.OrgRole = testCase.role
sc.reqContext.ReplaceAllParams(map[string]string{":uid": result.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.Result.UID})
resp = sc.service.deleteHandler(sc.reqContext) resp = sc.service.deleteHandler(sc.reqContext)
require.Equal(t, testCase.status, resp.Status()) require.Equal(t, testCase.status, resp.Status())
}) })
@ -147,7 +148,7 @@ func TestLibraryElementPermissions(t *testing.T) {
sc.reqContext.SignedInUser.OrgRole = testCase.role sc.reqContext.SignedInUser.OrgRole = testCase.role
cmd := patchLibraryElementCommand{FolderID: 0, Version: 1, Kind: int64(models.PanelElement)} cmd := patchLibraryElementCommand{FolderID: 0, Version: 1, Kind: int64(models.PanelElement)}
sc.reqContext.ReplaceAllParams(map[string]string{":uid": result.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.Result.UID})
resp = sc.service.patchHandler(sc.reqContext, cmd) resp = sc.service.patchHandler(sc.reqContext, cmd)
require.Equal(t, testCase.status, resp.Status()) require.Equal(t, testCase.status, resp.Status())
}) })
@ -161,7 +162,7 @@ func TestLibraryElementPermissions(t *testing.T) {
sc.reqContext.SignedInUser.OrgRole = testCase.role sc.reqContext.SignedInUser.OrgRole = testCase.role
cmd := patchLibraryElementCommand{FolderID: folder.Id, Version: 1, Kind: int64(models.PanelElement)} cmd := patchLibraryElementCommand{FolderID: folder.Id, Version: 1, Kind: int64(models.PanelElement)}
sc.reqContext.ReplaceAllParams(map[string]string{":uid": result.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.Result.UID})
resp = sc.service.patchHandler(sc.reqContext, cmd) resp = sc.service.patchHandler(sc.reqContext, cmd)
require.Equal(t, testCase.status, resp.Status()) require.Equal(t, testCase.status, resp.Status())
}) })
@ -173,7 +174,7 @@ func TestLibraryElementPermissions(t *testing.T) {
result := validateAndUnMarshalResponse(t, resp) result := validateAndUnMarshalResponse(t, resp)
sc.reqContext.SignedInUser.OrgRole = testCase.role sc.reqContext.SignedInUser.OrgRole = testCase.role
sc.reqContext.ReplaceAllParams(map[string]string{":uid": result.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.Result.UID})
resp = sc.service.deleteHandler(sc.reqContext) resp = sc.service.deleteHandler(sc.reqContext)
require.Equal(t, testCase.status, resp.Status()) require.Equal(t, testCase.status, resp.Status())
}) })
@ -206,7 +207,7 @@ func TestLibraryElementPermissions(t *testing.T) {
sc.reqContext.SignedInUser.OrgRole = testCase.role sc.reqContext.SignedInUser.OrgRole = testCase.role
cmd := patchLibraryElementCommand{FolderID: -100, Version: 1, Kind: int64(models.PanelElement)} cmd := patchLibraryElementCommand{FolderID: -100, Version: 1, Kind: int64(models.PanelElement)}
sc.reqContext.ReplaceAllParams(map[string]string{":uid": result.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.Result.UID})
resp = sc.service.patchHandler(sc.reqContext, cmd) resp = sc.service.patchHandler(sc.reqContext, cmd)
require.Equal(t, 404, resp.Status()) require.Equal(t, 404, resp.Status())
}) })
@ -241,7 +242,7 @@ func TestLibraryElementPermissions(t *testing.T) {
sc.reqContext.SignedInUser.OrgRole = testCase.role sc.reqContext.SignedInUser.OrgRole = testCase.role
for i, result := range results { for i, result := range results {
sc.reqContext.ReplaceAllParams(map[string]string{":uid": result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.UID})
resp := sc.service.getHandler(sc.reqContext) resp := sc.service.getHandler(sc.reqContext)
require.Equal(t, testCase.statuses[i], resp.Status()) require.Equal(t, testCase.statuses[i], resp.Status())
} }
@ -260,7 +261,7 @@ func TestLibraryElementPermissions(t *testing.T) {
result.Result.Meta.FolderUID = "" result.Result.Meta.FolderUID = ""
sc.reqContext.SignedInUser.OrgRole = testCase.role sc.reqContext.SignedInUser.OrgRole = testCase.role
sc.reqContext.ReplaceAllParams(map[string]string{":uid": result.Result.UID}) sc.ctx.Req = macaron.SetURLParams(sc.ctx.Req, map[string]string{":uid": result.Result.UID})
resp = sc.service.getHandler(sc.reqContext) resp = sc.service.getHandler(sc.reqContext)
require.Equal(t, 200, resp.Status()) require.Equal(t, 200, resp.Status())
var actual libraryElementResult var actual libraryElementResult

@ -40,6 +40,7 @@ import (
"github.com/gobwas/glob" "github.com/gobwas/glob"
"github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/live" "github.com/grafana/grafana-plugin-sdk-go/live"
"gopkg.in/macaron.v1"
"gopkg.in/redis.v5" "gopkg.in/redis.v5"
) )
@ -307,7 +308,7 @@ func ProvideService(plugCtxProvider *plugincontext.Provider, cfg *setting.Cfg, r
g.pushWebsocketHandler = func(ctx *models.ReqContext) { g.pushWebsocketHandler = func(ctx *models.ReqContext) {
user := ctx.SignedInUser user := ctx.SignedInUser
newCtx := livecontext.SetContextSignedUser(ctx.Req.Context(), user) newCtx := livecontext.SetContextSignedUser(ctx.Req.Context(), user)
newCtx = livecontext.SetContextStreamID(newCtx, ctx.Params(":streamId")) newCtx = livecontext.SetContextStreamID(newCtx, macaron.Params(ctx.Req)[":streamId"])
r := ctx.Req.WithContext(newCtx) r := ctx.Req.WithContext(newCtx)
pushWSHandler.ServeHTTP(ctx.Resp, r) pushWSHandler.ServeHTTP(ctx.Resp, r)
} }
@ -816,7 +817,7 @@ func (g *GrafanaLive) HandleListHTTP(c *models.ReqContext) response.Response {
// HandleInfoHTTP special http response for // HandleInfoHTTP special http response for
func (g *GrafanaLive) HandleInfoHTTP(ctx *models.ReqContext) response.Response { func (g *GrafanaLive) HandleInfoHTTP(ctx *models.ReqContext) response.Response {
path := ctx.Params("*") path := macaron.Params(ctx.Req)["*"]
if path == "grafana/dashboards/gitops" { if path == "grafana/dashboards/gitops" {
return response.JSON(200, util.DynMap{ return response.JSON(200, util.DynMap{
"active": g.GrafanaScope.Dashboards.HasGitOpsObserver(ctx.SignedInUser.OrgId), "active": g.GrafanaScope.Dashboards.HasGitOpsObserver(ctx.SignedInUser.OrgId),

@ -14,6 +14,7 @@ import (
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
liveDto "github.com/grafana/grafana-plugin-sdk-go/live" liveDto "github.com/grafana/grafana-plugin-sdk-go/live"
"gopkg.in/macaron.v1"
) )
var ( var (
@ -45,7 +46,7 @@ func (g *Gateway) Run(ctx context.Context) error {
} }
func (g *Gateway) Handle(ctx *models.ReqContext) { func (g *Gateway) Handle(ctx *models.ReqContext) {
streamID := ctx.Params(":streamId") streamID := macaron.Params(ctx.Req)[":streamId"]
stream, err := g.GrafanaLive.ManagedStreamRunner.GetOrCreateStream(ctx.SignedInUser.OrgId, liveDto.ScopeStream, streamID) stream, err := g.GrafanaLive.ManagedStreamRunner.GetOrCreateStream(ctx.SignedInUser.OrgId, liveDto.ScopeStream, streamID)
if err != nil { if err != nil {
@ -96,8 +97,8 @@ func (g *Gateway) Handle(ctx *models.ReqContext) {
} }
func (g *Gateway) HandlePath(ctx *models.ReqContext) { func (g *Gateway) HandlePath(ctx *models.ReqContext) {
streamID := ctx.Params(":streamId") streamID := macaron.Params(ctx.Req)[":streamId"]
path := ctx.Params(":path") path := macaron.Params(ctx.Req)[":path"]
body, err := io.ReadAll(ctx.Req.Body) body, err := io.ReadAll(ctx.Req.Body)
if err != nil { if err != nil {

@ -17,6 +17,7 @@ import (
"github.com/grafana/grafana/pkg/services/ngalert/notifier" "github.com/grafana/grafana/pkg/services/ngalert/notifier"
"github.com/grafana/grafana/pkg/services/ngalert/store" "github.com/grafana/grafana/pkg/services/ngalert/store"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
"gopkg.in/macaron.v1"
) )
const ( const (
@ -154,7 +155,7 @@ func (srv AlertmanagerSrv) RouteDeleteSilence(c *models.ReqContext) response.Res
return errResp return errResp
} }
silenceID := c.Params(":SilenceId") silenceID := macaron.Params(c.Req)[":SilenceId"]
if err := am.DeleteSilence(silenceID); err != nil { if err := am.DeleteSilence(silenceID); err != nil {
if errors.Is(err, notifier.ErrSilenceNotFound) { if errors.Is(err, notifier.ErrSilenceNotFound) {
return ErrResp(http.StatusNotFound, err, "") return ErrResp(http.StatusNotFound, err, "")
@ -281,7 +282,7 @@ func (srv AlertmanagerSrv) RouteGetSilence(c *models.ReqContext) response.Respon
return errResp return errResp
} }
silenceID := c.Params(":SilenceId") silenceID := macaron.Params(c.Req)[":SilenceId"]
gettableSilence, err := am.GetSilence(silenceID) gettableSilence, err := am.GetSilence(silenceID)
if err != nil { if err != nil {
if errors.Is(err, notifier.ErrSilenceNotFound) { if errors.Is(err, notifier.ErrSilenceNotFound) {

@ -10,6 +10,7 @@ import (
"github.com/grafana/grafana/pkg/services/ngalert/state" "github.com/grafana/grafana/pkg/services/ngalert/state"
"github.com/grafana/grafana/pkg/services/ngalert/store" "github.com/grafana/grafana/pkg/services/ngalert/store"
"github.com/grafana/grafana/pkg/services/quota" "github.com/grafana/grafana/pkg/services/quota"
"gopkg.in/macaron.v1"
"github.com/grafana/grafana/pkg/api/apierrors" "github.com/grafana/grafana/pkg/api/apierrors"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
@ -30,7 +31,7 @@ type RulerSrv struct {
} }
func (srv RulerSrv) RouteDeleteNamespaceRulesConfig(c *models.ReqContext) response.Response { func (srv RulerSrv) RouteDeleteNamespaceRulesConfig(c *models.ReqContext) response.Response {
namespaceTitle := c.Params(":Namespace") namespaceTitle := macaron.Params(c.Req)[":Namespace"]
namespace, err := srv.store.GetNamespaceByTitle(c.Req.Context(), namespaceTitle, c.SignedInUser.OrgId, c.SignedInUser, true) namespace, err := srv.store.GetNamespaceByTitle(c.Req.Context(), namespaceTitle, c.SignedInUser.OrgId, c.SignedInUser, true)
if err != nil { if err != nil {
return toNamespaceErrorResponse(err) return toNamespaceErrorResponse(err)
@ -49,12 +50,12 @@ func (srv RulerSrv) RouteDeleteNamespaceRulesConfig(c *models.ReqContext) respon
} }
func (srv RulerSrv) RouteDeleteRuleGroupConfig(c *models.ReqContext) response.Response { func (srv RulerSrv) RouteDeleteRuleGroupConfig(c *models.ReqContext) response.Response {
namespaceTitle := c.Params(":Namespace") namespaceTitle := macaron.Params(c.Req)[":Namespace"]
namespace, err := srv.store.GetNamespaceByTitle(c.Req.Context(), namespaceTitle, c.SignedInUser.OrgId, c.SignedInUser, true) namespace, err := srv.store.GetNamespaceByTitle(c.Req.Context(), namespaceTitle, c.SignedInUser.OrgId, c.SignedInUser, true)
if err != nil { if err != nil {
return toNamespaceErrorResponse(err) return toNamespaceErrorResponse(err)
} }
ruleGroup := c.Params(":Groupname") ruleGroup := macaron.Params(c.Req)[":Groupname"]
uids, err := srv.store.DeleteRuleGroupAlertRules(c.SignedInUser.OrgId, namespace.Uid, ruleGroup) uids, err := srv.store.DeleteRuleGroupAlertRules(c.SignedInUser.OrgId, namespace.Uid, ruleGroup)
if err != nil { if err != nil {
@ -72,7 +73,7 @@ func (srv RulerSrv) RouteDeleteRuleGroupConfig(c *models.ReqContext) response.Re
} }
func (srv RulerSrv) RouteGetNamespaceRulesConfig(c *models.ReqContext) response.Response { func (srv RulerSrv) RouteGetNamespaceRulesConfig(c *models.ReqContext) response.Response {
namespaceTitle := c.Params(":Namespace") namespaceTitle := macaron.Params(c.Req)[":Namespace"]
namespace, err := srv.store.GetNamespaceByTitle(c.Req.Context(), namespaceTitle, c.SignedInUser.OrgId, c.SignedInUser, false) namespace, err := srv.store.GetNamespaceByTitle(c.Req.Context(), namespaceTitle, c.SignedInUser.OrgId, c.SignedInUser, false)
if err != nil { if err != nil {
return toNamespaceErrorResponse(err) return toNamespaceErrorResponse(err)
@ -113,13 +114,13 @@ func (srv RulerSrv) RouteGetNamespaceRulesConfig(c *models.ReqContext) response.
} }
func (srv RulerSrv) RouteGetRulegGroupConfig(c *models.ReqContext) response.Response { func (srv RulerSrv) RouteGetRulegGroupConfig(c *models.ReqContext) response.Response {
namespaceTitle := c.Params(":Namespace") namespaceTitle := macaron.Params(c.Req)[":Namespace"]
namespace, err := srv.store.GetNamespaceByTitle(c.Req.Context(), namespaceTitle, c.SignedInUser.OrgId, c.SignedInUser, false) namespace, err := srv.store.GetNamespaceByTitle(c.Req.Context(), namespaceTitle, c.SignedInUser.OrgId, c.SignedInUser, false)
if err != nil { if err != nil {
return toNamespaceErrorResponse(err) return toNamespaceErrorResponse(err)
} }
ruleGroup := c.Params(":Groupname") ruleGroup := macaron.Params(c.Req)[":Groupname"]
q := ngmodels.ListRuleGroupAlertRulesQuery{ q := ngmodels.ListRuleGroupAlertRulesQuery{
OrgID: c.SignedInUser.OrgId, OrgID: c.SignedInUser.OrgId,
NamespaceUID: namespace.Uid, NamespaceUID: namespace.Uid,
@ -213,7 +214,7 @@ func (srv RulerSrv) RouteGetRulesConfig(c *models.ReqContext) response.Response
} }
func (srv RulerSrv) RoutePostNameRulesConfig(c *models.ReqContext, ruleGroupConfig apimodels.PostableRuleGroupConfig) response.Response { func (srv RulerSrv) RoutePostNameRulesConfig(c *models.ReqContext, ruleGroupConfig apimodels.PostableRuleGroupConfig) response.Response {
namespaceTitle := c.Params(":Namespace") namespaceTitle := macaron.Params(c.Req)[":Namespace"]
namespace, err := srv.store.GetNamespaceByTitle(c.Req.Context(), namespaceTitle, c.SignedInUser.OrgId, c.SignedInUser, true) namespace, err := srv.store.GetNamespaceByTitle(c.Req.Context(), namespaceTitle, c.SignedInUser.OrgId, c.SignedInUser, true)
if err != nil { if err != nil {
return toNamespaceErrorResponse(err) return toNamespaceErrorResponse(err)

@ -15,6 +15,7 @@ import (
"github.com/grafana/grafana/pkg/services/ngalert/eval" "github.com/grafana/grafana/pkg/services/ngalert/eval"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/tsdb" "github.com/grafana/grafana/pkg/tsdb"
"gopkg.in/macaron.v1"
) )
type TestingApiSrv struct { type TestingApiSrv struct {
@ -26,7 +27,7 @@ type TestingApiSrv struct {
} }
func (srv TestingApiSrv) RouteTestRuleConfig(c *models.ReqContext, body apimodels.TestRulePayload) response.Response { func (srv TestingApiSrv) RouteTestRuleConfig(c *models.ReqContext, body apimodels.TestRulePayload) response.Response {
recipient := c.Params("Recipient") recipient := macaron.Params(c.Req)[":Recipient"]
if recipient == apimodels.GrafanaBackend.String() { if recipient == apimodels.GrafanaBackend.String() {
if body.Type() != apimodels.GrafanaBackend || body.GrafanaManagedCondition == nil { if body.Type() != apimodels.GrafanaBackend || body.GrafanaManagedCondition == nil {
return ErrResp(http.StatusBadRequest, errors.New("unexpected payload"), "") return ErrResp(http.StatusBadRequest, errors.New("unexpected payload"), "")

@ -10,6 +10,7 @@ import (
"github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/models"
apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions" apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"gopkg.in/macaron.v1"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
@ -83,7 +84,7 @@ func (am *LotexAM) RouteDeleteSilence(ctx *models.ReqContext) response.Response
http.MethodDelete, http.MethodDelete,
withPath( withPath(
*ctx.Req.URL, *ctx.Req.URL,
fmt.Sprintf(amSilencePath, ctx.Params(":SilenceId")), fmt.Sprintf(amSilencePath, macaron.Params(ctx.Req)[":SilenceId"]),
), ),
nil, nil,
messageExtractor, messageExtractor,
@ -139,7 +140,7 @@ func (am *LotexAM) RouteGetSilence(ctx *models.ReqContext) response.Response {
http.MethodGet, http.MethodGet,
withPath( withPath(
*ctx.Req.URL, *ctx.Req.URL,
fmt.Sprintf(amSilencePath, ctx.Params(":SilenceId")), fmt.Sprintf(amSilencePath, macaron.Params(ctx.Req)[":SilenceId"]),
), ),
nil, nil,
jsonExtractor(&apimodels.GettableSilence{}), jsonExtractor(&apimodels.GettableSilence{}),

@ -76,7 +76,7 @@ func (p *LotexProm) RouteGetRuleStatuses(ctx *models.ReqContext) response.Respon
} }
func (p *LotexProm) getEndpoints(ctx *models.ReqContext) (*promEndpoints, error) { func (p *LotexProm) getEndpoints(ctx *models.ReqContext) (*promEndpoints, error) {
ds, err := p.DataProxy.DataSourceCache.GetDatasource(ctx.ParamsInt64("Recipient"), ctx.SignedInUser, ctx.SkipCache) ds, err := p.DataProxy.DataSourceCache.GetDatasource(ctx.ParamsInt64(":Recipient"), ctx.SignedInUser, ctx.SkipCache)
if err != nil { if err != nil {
return nil, err return nil, err
} }

@ -7,6 +7,7 @@ import (
"net/url" "net/url"
apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions" apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
"gopkg.in/macaron.v1"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
"github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/response"
@ -41,7 +42,7 @@ func (r *LotexRuler) RouteDeleteNamespaceRulesConfig(ctx *models.ReqContext) res
http.MethodDelete, http.MethodDelete,
withPath( withPath(
*ctx.Req.URL, *ctx.Req.URL,
fmt.Sprintf("%s/%s", legacyRulerPrefix, ctx.Params("Namespace")), fmt.Sprintf("%s/%s", legacyRulerPrefix, macaron.Params(ctx.Req)[":Namespace"]),
), ),
nil, nil,
messageExtractor, messageExtractor,
@ -62,8 +63,8 @@ func (r *LotexRuler) RouteDeleteRuleGroupConfig(ctx *models.ReqContext) response
fmt.Sprintf( fmt.Sprintf(
"%s/%s/%s", "%s/%s/%s",
legacyRulerPrefix, legacyRulerPrefix,
ctx.Params("Namespace"), macaron.Params(ctx.Req)[":Namespace"],
ctx.Params("Groupname"), macaron.Params(ctx.Req)[":Groupname"],
), ),
), ),
nil, nil,
@ -85,7 +86,7 @@ func (r *LotexRuler) RouteGetNamespaceRulesConfig(ctx *models.ReqContext) respon
fmt.Sprintf( fmt.Sprintf(
"%s/%s", "%s/%s",
legacyRulerPrefix, legacyRulerPrefix,
ctx.Params("Namespace"), macaron.Params(ctx.Req)[":Namespace"],
), ),
), ),
nil, nil,
@ -107,8 +108,8 @@ func (r *LotexRuler) RouteGetRulegGroupConfig(ctx *models.ReqContext) response.R
fmt.Sprintf( fmt.Sprintf(
"%s/%s/%s", "%s/%s/%s",
legacyRulerPrefix, legacyRulerPrefix,
ctx.Params("Namespace"), macaron.Params(ctx.Req)[":Namespace"],
ctx.Params("Groupname"), macaron.Params(ctx.Req)[":Groupname"],
), ),
), ),
nil, nil,
@ -144,13 +145,13 @@ func (r *LotexRuler) RoutePostNameRulesConfig(ctx *models.ReqContext, conf apimo
if err != nil { if err != nil {
return ErrResp(500, err, "Failed marshal rule group") return ErrResp(500, err, "Failed marshal rule group")
} }
ns := ctx.Params("Namespace") ns := macaron.Params(ctx.Req)[":Namespace"]
u := withPath(*ctx.Req.URL, fmt.Sprintf("%s/%s", legacyRulerPrefix, ns)) u := withPath(*ctx.Req.URL, fmt.Sprintf("%s/%s", legacyRulerPrefix, ns))
return r.withReq(ctx, http.MethodPost, u, bytes.NewBuffer(yml), jsonExtractor(nil), nil) return r.withReq(ctx, http.MethodPost, u, bytes.NewBuffer(yml), jsonExtractor(nil), nil)
} }
func (r *LotexRuler) getPrefix(ctx *models.ReqContext) (string, error) { func (r *LotexRuler) getPrefix(ctx *models.ReqContext) (string, error) {
ds, err := r.DataProxy.DataSourceCache.GetDatasource(ctx.ParamsInt64("Recipient"), ctx.SignedInUser, ctx.SkipCache) ds, err := r.DataProxy.DataSourceCache.GetDatasource(ctx.ParamsInt64(":Recipient"), ctx.SignedInUser, ctx.SkipCache)
if err != nil { if err != nil {
return "", err return "", err
} }

@ -40,7 +40,7 @@ func toMacaronPath(path string) string {
} }
func backendType(ctx *models.ReqContext, cache datasources.CacheService) (apimodels.Backend, error) { func backendType(ctx *models.ReqContext, cache datasources.CacheService) (apimodels.Backend, error) {
recipient := ctx.Params("Recipient") recipient := macaron.Params(ctx.Req)[":Recipient"]
if recipient == apimodels.GrafanaBackend.String() { if recipient == apimodels.GrafanaBackend.String() {
return apimodels.GrafanaBackend, nil return apimodels.GrafanaBackend, nil
} }
@ -104,7 +104,7 @@ func (p *AlertingProxy) withReq(
} }
newCtx, resp := replacedResponseWriter(ctx) newCtx, resp := replacedResponseWriter(ctx)
newCtx.Req = req newCtx.Req = req
p.DataProxy.ProxyDatasourceRequestWithID(newCtx, ctx.ParamsInt64("Recipient")) p.DataProxy.ProxyDatasourceRequestWithID(newCtx, ctx.ParamsInt64(":Recipient"))
status := resp.Status() status := resp.Status()
if status >= 400 { if status >= 400 {

@ -263,7 +263,7 @@ func Instrument(
// TODO: We could look up the datasource type via our datasource service // TODO: We could look up the datasource type via our datasource service
var backend string var backend string
recipient := c.Params("Recipient") recipient := macaron.Params(c.Req)[":Recipient"]
if recipient == apimodels.GrafanaBackend.String() || recipient == "" { if recipient == apimodels.GrafanaBackend.String() || recipient == "" {
backend = GrafanaBackend backend = GrafanaBackend
} else { } else {

Loading…
Cancel
Save