Commit b818e9f6 by Marcus Efraimsson

Merge branch 'master' into 11306-sql-table-time

parents f0f41c2a 22fffe0d
+++ +++
title = "Variables" title = "Variables"
keywords = ["grafana", "templating", "documentation", "guide"] keywords = ["grafana", "templating", "documentation", "guide", "template", "variable"]
type = "docs" type = "docs"
[menu.docs] [menu.docs]
name = "Variables" name = "Variables"
...@@ -80,6 +80,73 @@ Option | Description ...@@ -80,6 +80,73 @@ Option | Description
*Regex* | Regex to filter or capture specific parts of the names return by your data source query. Optional. *Regex* | Regex to filter or capture specific parts of the names return by your data source query. Optional.
*Sort* | Define sort order for options in dropdown. **Disabled** means that the order of options returned by your data source query will be used. *Sort* | Define sort order for options in dropdown. **Disabled** means that the order of options returned by your data source query will be used.
#### Using regex to filter/modify values in the Variable dropdown
Using the Regex Query Option, you filter the list of options returned by the Variable query or modify the options returned.
Examples of filtering on the following list of options:
```text
backend_01
backend_02
backend_03
backend_04
```
##### Filter so that only the options that end with `01` or `02` are returned:
Regex:
```regex
/.*[01|02]/
```
Result:
```text
backend_01
backend_02
```
##### Filter and modify the options using a regex capture group to return part of the text:
Regex:
```regex
/.*(01|02)/
```
Result:
```text
01
02
```
#### Filter and modify - Prometheus Example
List of options:
```text
up{instance="demo.robustperception.io:9090",job="prometheus"} 1 1521630638000
up{instance="demo.robustperception.io:9093",job="alertmanager"} 1 1521630638000
up{instance="demo.robustperception.io:9100",job="node"} 1 1521630638000
```
Regex:
```regex
/.*instance="([^"]*).*/
```
Result:
```text
demo.robustperception.io:9090
demo.robustperception.io:9093
demo.robustperception.io:9100
```
### Query expressions ### Query expressions
The query expressions are different for each data source. The query expressions are different for each data source.
......
...@@ -47,14 +47,14 @@ func AdminCreateUser(c *m.ReqContext, form dtos.AdminCreateUserForm) { ...@@ -47,14 +47,14 @@ func AdminCreateUser(c *m.ReqContext, form dtos.AdminCreateUserForm) {
} }
func AdminUpdateUserPassword(c *m.ReqContext, form dtos.AdminUpdateUserPasswordForm) { func AdminUpdateUserPassword(c *m.ReqContext, form dtos.AdminUpdateUserPasswordForm) {
userId := c.ParamsInt64(":id") userID := c.ParamsInt64(":id")
if len(form.Password) < 4 { if len(form.Password) < 4 {
c.JsonApiErr(400, "New password too short", nil) c.JsonApiErr(400, "New password too short", nil)
return return
} }
userQuery := m.GetUserByIdQuery{Id: userId} userQuery := m.GetUserByIdQuery{Id: userID}
if err := bus.Dispatch(&userQuery); err != nil { if err := bus.Dispatch(&userQuery); err != nil {
c.JsonApiErr(500, "Could not read user from database", err) c.JsonApiErr(500, "Could not read user from database", err)
...@@ -64,7 +64,7 @@ func AdminUpdateUserPassword(c *m.ReqContext, form dtos.AdminUpdateUserPasswordF ...@@ -64,7 +64,7 @@ func AdminUpdateUserPassword(c *m.ReqContext, form dtos.AdminUpdateUserPasswordF
passwordHashed := util.EncodePassword(form.Password, userQuery.Result.Salt) passwordHashed := util.EncodePassword(form.Password, userQuery.Result.Salt)
cmd := m.ChangeUserPasswordCommand{ cmd := m.ChangeUserPasswordCommand{
UserId: userId, UserId: userID,
NewPassword: passwordHashed, NewPassword: passwordHashed,
} }
...@@ -77,10 +77,10 @@ func AdminUpdateUserPassword(c *m.ReqContext, form dtos.AdminUpdateUserPasswordF ...@@ -77,10 +77,10 @@ func AdminUpdateUserPassword(c *m.ReqContext, form dtos.AdminUpdateUserPasswordF
} }
func AdminUpdateUserPermissions(c *m.ReqContext, form dtos.AdminUpdateUserPermissionsForm) { func AdminUpdateUserPermissions(c *m.ReqContext, form dtos.AdminUpdateUserPermissionsForm) {
userId := c.ParamsInt64(":id") userID := c.ParamsInt64(":id")
cmd := m.UpdateUserPermissionsCommand{ cmd := m.UpdateUserPermissionsCommand{
UserId: userId, UserId: userID,
IsGrafanaAdmin: form.IsGrafanaAdmin, IsGrafanaAdmin: form.IsGrafanaAdmin,
} }
...@@ -93,9 +93,9 @@ func AdminUpdateUserPermissions(c *m.ReqContext, form dtos.AdminUpdateUserPermis ...@@ -93,9 +93,9 @@ func AdminUpdateUserPermissions(c *m.ReqContext, form dtos.AdminUpdateUserPermis
} }
func AdminDeleteUser(c *m.ReqContext) { func AdminDeleteUser(c *m.ReqContext) {
userId := c.ParamsInt64(":id") userID := c.ParamsInt64(":id")
cmd := m.DeleteUserCommand{UserId: userId} cmd := m.DeleteUserCommand{UserId: userID}
if err := bus.Dispatch(&cmd); err != nil { if err := bus.Dispatch(&cmd); err != nil {
c.JsonApiErr(500, "Failed to delete user", err) c.JsonApiErr(500, "Failed to delete user", err)
......
...@@ -26,9 +26,9 @@ func ValidateOrgAlert(c *m.ReqContext) { ...@@ -26,9 +26,9 @@ func ValidateOrgAlert(c *m.ReqContext) {
} }
func GetAlertStatesForDashboard(c *m.ReqContext) Response { func GetAlertStatesForDashboard(c *m.ReqContext) Response {
dashboardId := c.QueryInt64("dashboardId") dashboardID := c.QueryInt64("dashboardId")
if dashboardId == 0 { if dashboardID == 0 {
return ApiError(400, "Missing query parameter dashboardId", nil) return ApiError(400, "Missing query parameter dashboardId", nil)
} }
...@@ -151,7 +151,7 @@ func GetAlertNotifications(c *m.ReqContext) Response { ...@@ -151,7 +151,7 @@ func GetAlertNotifications(c *m.ReqContext) Response {
return Json(200, result) return Json(200, result)
} }
func GetAlertNotificationById(c *m.ReqContext) Response { func GetAlertNotificationByID(c *m.ReqContext) Response {
query := &m.GetAlertNotificationsQuery{ query := &m.GetAlertNotificationsQuery{
OrgId: c.OrgId, OrgId: c.OrgId,
Id: c.ParamsInt64("notificationId"), Id: c.ParamsInt64("notificationId"),
......
...@@ -52,7 +52,7 @@ func (e *CreateAnnotationError) Error() string { ...@@ -52,7 +52,7 @@ func (e *CreateAnnotationError) Error() string {
} }
func PostAnnotation(c *m.ReqContext, cmd dtos.PostAnnotationsCmd) Response { func PostAnnotation(c *m.ReqContext, cmd dtos.PostAnnotationsCmd) Response {
if canSave, err := canSaveByDashboardId(c, cmd.DashboardId); err != nil || !canSave { if canSave, err := canSaveByDashboardID(c, cmd.DashboardId); err != nil || !canSave {
return dashboardGuardianResponse(err) return dashboardGuardianResponse(err)
} }
...@@ -179,18 +179,18 @@ func PostGraphiteAnnotation(c *m.ReqContext, cmd dtos.PostGraphiteAnnotationsCmd ...@@ -179,18 +179,18 @@ func PostGraphiteAnnotation(c *m.ReqContext, cmd dtos.PostGraphiteAnnotationsCmd
} }
func UpdateAnnotation(c *m.ReqContext, cmd dtos.UpdateAnnotationsCmd) Response { func UpdateAnnotation(c *m.ReqContext, cmd dtos.UpdateAnnotationsCmd) Response {
annotationId := c.ParamsInt64(":annotationId") annotationID := c.ParamsInt64(":annotationId")
repo := annotations.GetRepository() repo := annotations.GetRepository()
if resp := canSave(c, repo, annotationId); resp != nil { if resp := canSave(c, repo, annotationID); resp != nil {
return resp return resp
} }
item := annotations.Item{ item := annotations.Item{
OrgId: c.OrgId, OrgId: c.OrgId,
UserId: c.UserId, UserId: c.UserId,
Id: annotationId, Id: annotationID,
Epoch: cmd.Time / 1000, Epoch: cmd.Time / 1000,
Text: cmd.Text, Text: cmd.Text,
Tags: cmd.Tags, Tags: cmd.Tags,
...@@ -254,14 +254,14 @@ func DeleteAnnotationById(c *m.ReqContext) Response { ...@@ -254,14 +254,14 @@ func DeleteAnnotationById(c *m.ReqContext) Response {
func DeleteAnnotationRegion(c *m.ReqContext) Response { func DeleteAnnotationRegion(c *m.ReqContext) Response {
repo := annotations.GetRepository() repo := annotations.GetRepository()
regionId := c.ParamsInt64(":regionId") regionID := c.ParamsInt64(":regionId")
if resp := canSave(c, repo, regionId); resp != nil { if resp := canSave(c, repo, regionID); resp != nil {
return resp return resp
} }
err := repo.Delete(&annotations.DeleteParams{ err := repo.Delete(&annotations.DeleteParams{
RegionId: regionId, RegionId: regionID,
}) })
if err != nil { if err != nil {
...@@ -271,13 +271,13 @@ func DeleteAnnotationRegion(c *m.ReqContext) Response { ...@@ -271,13 +271,13 @@ func DeleteAnnotationRegion(c *m.ReqContext) Response {
return ApiSuccess("Annotation region deleted") return ApiSuccess("Annotation region deleted")
} }
func canSaveByDashboardId(c *m.ReqContext, dashboardId int64) (bool, error) { func canSaveByDashboardID(c *m.ReqContext, dashboardID int64) (bool, error) {
if dashboardId == 0 && !c.SignedInUser.HasRole(m.ROLE_EDITOR) { if dashboardID == 0 && !c.SignedInUser.HasRole(m.ROLE_EDITOR) {
return false, nil return false, nil
} }
if dashboardId > 0 { if dashboardID > 0 {
guardian := guardian.New(dashboardId, c.OrgId, c.SignedInUser) guardian := guardian.New(dashboardID, c.OrgId, c.SignedInUser)
if canEdit, err := guardian.CanEdit(); err != nil || !canEdit { if canEdit, err := guardian.CanEdit(); err != nil || !canEdit {
return false, err return false, err
} }
...@@ -293,25 +293,25 @@ func canSave(c *m.ReqContext, repo annotations.Repository, annotationId int64) R ...@@ -293,25 +293,25 @@ func canSave(c *m.ReqContext, repo annotations.Repository, annotationId int64) R
return ApiError(500, "Could not find annotation to update", err) return ApiError(500, "Could not find annotation to update", err)
} }
dashboardId := items[0].DashboardId dashboardID := items[0].DashboardId
if canSave, err := canSaveByDashboardId(c, dashboardId); err != nil || !canSave { if canSave, err := canSaveByDashboardID(c, dashboardID); err != nil || !canSave {
return dashboardGuardianResponse(err) return dashboardGuardianResponse(err)
} }
return nil return nil
} }
func canSaveByRegionId(c *m.ReqContext, repo annotations.Repository, regionId int64) Response { func canSaveByRegionID(c *m.ReqContext, repo annotations.Repository, regionID int64) Response {
items, err := repo.Find(&annotations.ItemQuery{RegionId: regionId, OrgId: c.OrgId}) items, err := repo.Find(&annotations.ItemQuery{RegionId: regionID, OrgId: c.OrgId})
if err != nil || len(items) == 0 { if err != nil || len(items) == 0 {
return ApiError(500, "Could not find annotation to update", err) return ApiError(500, "Could not find annotation to update", err)
} }
dashboardId := items[0].DashboardId dashboardID := items[0].DashboardId
if canSave, err := canSaveByDashboardId(c, dashboardId); err != nil || !canSave { if canSave, err := canSaveByDashboardID(c, dashboardID); err != nil || !canSave {
return dashboardGuardianResponse(err) return dashboardGuardianResponse(err)
} }
......
...@@ -15,7 +15,7 @@ func (hs *HttpServer) registerRoutes() { ...@@ -15,7 +15,7 @@ func (hs *HttpServer) registerRoutes() {
reqGrafanaAdmin := middleware.Auth(&middleware.AuthOptions{ReqSignedIn: true, ReqGrafanaAdmin: true}) reqGrafanaAdmin := middleware.Auth(&middleware.AuthOptions{ReqSignedIn: true, ReqGrafanaAdmin: true})
reqEditorRole := middleware.RoleAuth(m.ROLE_EDITOR, m.ROLE_ADMIN) reqEditorRole := middleware.RoleAuth(m.ROLE_EDITOR, m.ROLE_ADMIN)
reqOrgAdmin := middleware.RoleAuth(m.ROLE_ADMIN) reqOrgAdmin := middleware.RoleAuth(m.ROLE_ADMIN)
redirectFromLegacyDashboardUrl := middleware.RedirectFromLegacyDashboardUrl() redirectFromLegacyDashboardUrl := middleware.RedirectFromLegacyDashboardURL()
redirectFromLegacyDashboardSoloUrl := middleware.RedirectFromLegacyDashboardSoloUrl() redirectFromLegacyDashboardSoloUrl := middleware.RedirectFromLegacyDashboardSoloUrl()
quota := middleware.Quota quota := middleware.Quota
bind := binding.Bind bind := binding.Bind
...@@ -110,7 +110,7 @@ func (hs *HttpServer) registerRoutes() { ...@@ -110,7 +110,7 @@ func (hs *HttpServer) registerRoutes() {
r.Get("/api/snapshots-delete/:key", reqEditorRole, wrap(DeleteDashboardSnapshot)) r.Get("/api/snapshots-delete/:key", reqEditorRole, wrap(DeleteDashboardSnapshot))
// api renew session based on remember cookie // api renew session based on remember cookie
r.Get("/api/login/ping", quota("session"), LoginApiPing) r.Get("/api/login/ping", quota("session"), LoginAPIPing)
// authed api // authed api
r.Group("/api", func(apiRoute RouteRegister) { r.Group("/api", func(apiRoute RouteRegister) {
...@@ -139,7 +139,7 @@ func (hs *HttpServer) registerRoutes() { ...@@ -139,7 +139,7 @@ func (hs *HttpServer) registerRoutes() {
apiRoute.Group("/users", func(usersRoute RouteRegister) { apiRoute.Group("/users", func(usersRoute RouteRegister) {
usersRoute.Get("/", wrap(SearchUsers)) usersRoute.Get("/", wrap(SearchUsers))
usersRoute.Get("/search", wrap(SearchUsersWithPaging)) usersRoute.Get("/search", wrap(SearchUsersWithPaging))
usersRoute.Get("/:id", wrap(GetUserById)) usersRoute.Get("/:id", wrap(GetUserByID))
usersRoute.Get("/:id/orgs", wrap(GetUserOrgList)) usersRoute.Get("/:id/orgs", wrap(GetUserOrgList))
// query parameters /users/lookup?loginOrEmail=admin@example.com // query parameters /users/lookup?loginOrEmail=admin@example.com
usersRoute.Get("/lookup", wrap(GetUserByLoginOrEmail)) usersRoute.Get("/lookup", wrap(GetUserByLoginOrEmail))
...@@ -149,11 +149,11 @@ func (hs *HttpServer) registerRoutes() { ...@@ -149,11 +149,11 @@ func (hs *HttpServer) registerRoutes() {
// team (admin permission required) // team (admin permission required)
apiRoute.Group("/teams", func(teamsRoute RouteRegister) { apiRoute.Group("/teams", func(teamsRoute RouteRegister) {
teamsRoute.Get("/:teamId", wrap(GetTeamById)) teamsRoute.Get("/:teamId", wrap(GetTeamByID))
teamsRoute.Get("/search", wrap(SearchTeams)) teamsRoute.Get("/search", wrap(SearchTeams))
teamsRoute.Post("/", bind(m.CreateTeamCommand{}), wrap(CreateTeam)) teamsRoute.Post("/", bind(m.CreateTeamCommand{}), wrap(CreateTeam))
teamsRoute.Put("/:teamId", bind(m.UpdateTeamCommand{}), wrap(UpdateTeam)) teamsRoute.Put("/:teamId", bind(m.UpdateTeamCommand{}), wrap(UpdateTeam))
teamsRoute.Delete("/:teamId", wrap(DeleteTeamById)) teamsRoute.Delete("/:teamId", wrap(DeleteTeamByID))
teamsRoute.Get("/:teamId/members", wrap(GetTeamMembers)) teamsRoute.Get("/:teamId/members", wrap(GetTeamMembers))
teamsRoute.Post("/:teamId/members", bind(m.AddTeamMemberCommand{}), wrap(AddTeamMember)) teamsRoute.Post("/:teamId/members", bind(m.AddTeamMemberCommand{}), wrap(AddTeamMember))
teamsRoute.Delete("/:teamId/members/:userId", wrap(RemoveTeamMember)) teamsRoute.Delete("/:teamId/members/:userId", wrap(RemoveTeamMember))
...@@ -192,10 +192,10 @@ func (hs *HttpServer) registerRoutes() { ...@@ -192,10 +192,10 @@ func (hs *HttpServer) registerRoutes() {
// orgs (admin routes) // orgs (admin routes)
apiRoute.Group("/orgs/:orgId", func(orgsRoute RouteRegister) { apiRoute.Group("/orgs/:orgId", func(orgsRoute RouteRegister) {
orgsRoute.Get("/", wrap(GetOrgById)) orgsRoute.Get("/", wrap(GetOrgByID))
orgsRoute.Put("/", bind(dtos.UpdateOrgForm{}), wrap(UpdateOrg)) orgsRoute.Put("/", bind(dtos.UpdateOrgForm{}), wrap(UpdateOrg))
orgsRoute.Put("/address", bind(dtos.UpdateOrgAddressForm{}), wrap(UpdateOrgAddress)) orgsRoute.Put("/address", bind(dtos.UpdateOrgAddressForm{}), wrap(UpdateOrgAddress))
orgsRoute.Delete("/", wrap(DeleteOrgById)) orgsRoute.Delete("/", wrap(DeleteOrgByID))
orgsRoute.Get("/users", wrap(GetOrgUsers)) orgsRoute.Get("/users", wrap(GetOrgUsers))
orgsRoute.Post("/users", bind(m.AddOrgUserCommand{}), wrap(AddOrgUser)) orgsRoute.Post("/users", bind(m.AddOrgUserCommand{}), wrap(AddOrgUser))
orgsRoute.Patch("/users/:userId", bind(m.UpdateOrgUserCommand{}), wrap(UpdateOrgUser)) orgsRoute.Patch("/users/:userId", bind(m.UpdateOrgUserCommand{}), wrap(UpdateOrgUser))
...@@ -211,9 +211,9 @@ func (hs *HttpServer) registerRoutes() { ...@@ -211,9 +211,9 @@ func (hs *HttpServer) registerRoutes() {
// auth api keys // auth api keys
apiRoute.Group("/auth/keys", func(keysRoute RouteRegister) { apiRoute.Group("/auth/keys", func(keysRoute RouteRegister) {
keysRoute.Get("/", wrap(GetApiKeys)) keysRoute.Get("/", wrap(GetAPIKeys))
keysRoute.Post("/", quota("api_key"), bind(m.AddApiKeyCommand{}), wrap(AddApiKey)) keysRoute.Post("/", quota("api_key"), bind(m.AddApiKeyCommand{}), wrap(AddAPIKey))
keysRoute.Delete("/:id", wrap(DeleteApiKey)) keysRoute.Delete("/:id", wrap(DeleteAPIKey))
}, reqOrgAdmin) }, reqOrgAdmin)
// Preferences // Preferences
...@@ -226,16 +226,16 @@ func (hs *HttpServer) registerRoutes() { ...@@ -226,16 +226,16 @@ func (hs *HttpServer) registerRoutes() {
datasourceRoute.Get("/", wrap(GetDataSources)) datasourceRoute.Get("/", wrap(GetDataSources))
datasourceRoute.Post("/", quota("data_source"), bind(m.AddDataSourceCommand{}), wrap(AddDataSource)) datasourceRoute.Post("/", quota("data_source"), bind(m.AddDataSourceCommand{}), wrap(AddDataSource))
datasourceRoute.Put("/:id", bind(m.UpdateDataSourceCommand{}), wrap(UpdateDataSource)) datasourceRoute.Put("/:id", bind(m.UpdateDataSourceCommand{}), wrap(UpdateDataSource))
datasourceRoute.Delete("/:id", wrap(DeleteDataSourceById)) datasourceRoute.Delete("/:id", wrap(DeleteDataSourceByID))
datasourceRoute.Delete("/name/:name", wrap(DeleteDataSourceByName)) datasourceRoute.Delete("/name/:name", wrap(DeleteDataSourceByName))
datasourceRoute.Get("/:id", wrap(GetDataSourceById)) datasourceRoute.Get("/:id", wrap(GetDataSourceByID))
datasourceRoute.Get("/name/:name", wrap(GetDataSourceByName)) datasourceRoute.Get("/name/:name", wrap(GetDataSourceByName))
}, reqOrgAdmin) }, reqOrgAdmin)
apiRoute.Get("/datasources/id/:name", wrap(GetDataSourceIdByName), reqSignedIn) apiRoute.Get("/datasources/id/:name", wrap(GetDataSourceIDByName), reqSignedIn)
apiRoute.Get("/plugins", wrap(GetPluginList)) apiRoute.Get("/plugins", wrap(GetPluginList))
apiRoute.Get("/plugins/:pluginId/settings", wrap(GetPluginSettingById)) apiRoute.Get("/plugins/:pluginId/settings", wrap(GetPluginSettingByID))
apiRoute.Get("/plugins/:pluginId/markdown/:name", wrap(GetPluginMarkdown)) apiRoute.Get("/plugins/:pluginId/markdown/:name", wrap(GetPluginMarkdown))
apiRoute.Group("/plugins", func(pluginRoute RouteRegister) { apiRoute.Group("/plugins", func(pluginRoute RouteRegister) {
...@@ -250,11 +250,11 @@ func (hs *HttpServer) registerRoutes() { ...@@ -250,11 +250,11 @@ func (hs *HttpServer) registerRoutes() {
// Folders // Folders
apiRoute.Group("/folders", func(folderRoute RouteRegister) { apiRoute.Group("/folders", func(folderRoute RouteRegister) {
folderRoute.Get("/", wrap(GetFolders)) folderRoute.Get("/", wrap(GetFolders))
folderRoute.Get("/id/:id", wrap(GetFolderById)) folderRoute.Get("/id/:id", wrap(GetFolderByID))
folderRoute.Post("/", bind(m.CreateFolderCommand{}), wrap(CreateFolder)) folderRoute.Post("/", bind(m.CreateFolderCommand{}), wrap(CreateFolder))
folderRoute.Group("/:uid", func(folderUidRoute RouteRegister) { folderRoute.Group("/:uid", func(folderUidRoute RouteRegister) {
folderUidRoute.Get("/", wrap(GetFolderByUid)) folderUidRoute.Get("/", wrap(GetFolderByUID))
folderUidRoute.Put("/", bind(m.UpdateFolderCommand{}), wrap(UpdateFolder)) folderUidRoute.Put("/", bind(m.UpdateFolderCommand{}), wrap(UpdateFolder))
folderUidRoute.Delete("/", wrap(DeleteFolder)) folderUidRoute.Delete("/", wrap(DeleteFolder))
...@@ -268,7 +268,7 @@ func (hs *HttpServer) registerRoutes() { ...@@ -268,7 +268,7 @@ func (hs *HttpServer) registerRoutes() {
// Dashboard // Dashboard
apiRoute.Group("/dashboards", func(dashboardRoute RouteRegister) { apiRoute.Group("/dashboards", func(dashboardRoute RouteRegister) {
dashboardRoute.Get("/uid/:uid", wrap(GetDashboard)) dashboardRoute.Get("/uid/:uid", wrap(GetDashboard))
dashboardRoute.Delete("/uid/:uid", wrap(DeleteDashboardByUid)) dashboardRoute.Delete("/uid/:uid", wrap(DeleteDashboardByUID))
dashboardRoute.Get("/db/:slug", wrap(GetDashboard)) dashboardRoute.Get("/db/:slug", wrap(GetDashboard))
dashboardRoute.Delete("/db/:slug", wrap(DeleteDashboard)) dashboardRoute.Delete("/db/:slug", wrap(DeleteDashboard))
...@@ -314,7 +314,7 @@ func (hs *HttpServer) registerRoutes() { ...@@ -314,7 +314,7 @@ func (hs *HttpServer) registerRoutes() {
// metrics // metrics
apiRoute.Post("/tsdb/query", bind(dtos.MetricRequest{}), wrap(QueryMetrics)) apiRoute.Post("/tsdb/query", bind(dtos.MetricRequest{}), wrap(QueryMetrics))
apiRoute.Get("/tsdb/testdata/scenarios", wrap(GetTestDataScenarios)) apiRoute.Get("/tsdb/testdata/scenarios", wrap(GetTestDataScenarios))
apiRoute.Get("/tsdb/testdata/gensql", reqGrafanaAdmin, wrap(GenerateSqlTestData)) apiRoute.Get("/tsdb/testdata/gensql", reqGrafanaAdmin, wrap(GenerateSQLTestData))
apiRoute.Get("/tsdb/testdata/random-walk", wrap(GetTestDataRandomWalk)) apiRoute.Get("/tsdb/testdata/random-walk", wrap(GetTestDataRandomWalk))
apiRoute.Group("/alerts", func(alertsRoute RouteRegister) { apiRoute.Group("/alerts", func(alertsRoute RouteRegister) {
...@@ -332,7 +332,7 @@ func (hs *HttpServer) registerRoutes() { ...@@ -332,7 +332,7 @@ func (hs *HttpServer) registerRoutes() {
alertNotifications.Post("/test", bind(dtos.NotificationTestCommand{}), wrap(NotificationTest)) alertNotifications.Post("/test", bind(dtos.NotificationTestCommand{}), wrap(NotificationTest))
alertNotifications.Post("/", bind(m.CreateAlertNotificationCommand{}), wrap(CreateAlertNotification)) alertNotifications.Post("/", bind(m.CreateAlertNotificationCommand{}), wrap(CreateAlertNotification))
alertNotifications.Put("/:notificationId", bind(m.UpdateAlertNotificationCommand{}), wrap(UpdateAlertNotification)) alertNotifications.Put("/:notificationId", bind(m.UpdateAlertNotificationCommand{}), wrap(UpdateAlertNotification))
alertNotifications.Get("/:notificationId", wrap(GetAlertNotificationById)) alertNotifications.Get("/:notificationId", wrap(GetAlertNotificationByID))
alertNotifications.Delete("/:notificationId", wrap(DeleteAlertNotification)) alertNotifications.Delete("/:notificationId", wrap(DeleteAlertNotification))
}, reqEditorRole) }, reqEditorRole)
......
...@@ -7,7 +7,7 @@ import ( ...@@ -7,7 +7,7 @@ import (
m "github.com/grafana/grafana/pkg/models" m "github.com/grafana/grafana/pkg/models"
) )
func GetApiKeys(c *m.ReqContext) Response { func GetAPIKeys(c *m.ReqContext) Response {
query := m.GetApiKeysQuery{OrgId: c.OrgId} query := m.GetApiKeysQuery{OrgId: c.OrgId}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
...@@ -26,7 +26,7 @@ func GetApiKeys(c *m.ReqContext) Response { ...@@ -26,7 +26,7 @@ func GetApiKeys(c *m.ReqContext) Response {
return Json(200, result) return Json(200, result)
} }
func DeleteApiKey(c *m.ReqContext) Response { func DeleteAPIKey(c *m.ReqContext) Response {
id := c.ParamsInt64(":id") id := c.ParamsInt64(":id")
cmd := &m.DeleteApiKeyCommand{Id: id, OrgId: c.OrgId} cmd := &m.DeleteApiKeyCommand{Id: id, OrgId: c.OrgId}
...@@ -39,7 +39,7 @@ func DeleteApiKey(c *m.ReqContext) Response { ...@@ -39,7 +39,7 @@ func DeleteApiKey(c *m.ReqContext) Response {
return ApiSuccess("API key deleted") return ApiSuccess("API key deleted")
} }
func AddApiKey(c *m.ReqContext, cmd m.AddApiKeyCommand) Response { func AddAPIKey(c *m.ReqContext, cmd m.AddApiKeyCommand) Response {
if !cmd.Role.IsValid() { if !cmd.Role.IsValid() {
return ApiError(400, "Invalid role specified", nil) return ApiError(400, "Invalid role specified", nil)
} }
......
...@@ -55,11 +55,11 @@ func InitAppPluginRoutes(r *macaron.Macaron) { ...@@ -55,11 +55,11 @@ func InitAppPluginRoutes(r *macaron.Macaron) {
} }
} }
func AppPluginRoute(route *plugins.AppPluginRoute, appId string) macaron.Handler { func AppPluginRoute(route *plugins.AppPluginRoute, appID string) macaron.Handler {
return func(c *m.ReqContext) { return func(c *m.ReqContext) {
path := c.Params("*") path := c.Params("*")
proxy := pluginproxy.NewApiPluginProxy(c, path, route, appId) proxy := pluginproxy.NewApiPluginProxy(c, path, route, appID)
proxy.Transport = pluginProxyTransport proxy.Transport = pluginProxyTransport
proxy.ServeHTTP(c.Resp, c.Req.Request) proxy.ServeHTTP(c.Resp, c.Req.Request)
} }
......
...@@ -22,12 +22,12 @@ import ( ...@@ -22,12 +22,12 @@ import (
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
) )
func isDashboardStarredByUser(c *m.ReqContext, dashId int64) (bool, error) { func isDashboardStarredByUser(c *m.ReqContext, dashID int64) (bool, error) {
if !c.IsSignedIn { if !c.IsSignedIn {
return false, nil return false, nil
} }
query := m.IsStarredByUserQuery{UserId: c.UserId, DashboardId: dashId} query := m.IsStarredByUserQuery{UserId: c.UserId, DashboardId: dashID}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
return false, err return false, err
} }
...@@ -114,24 +114,22 @@ func GetDashboard(c *m.ReqContext) Response { ...@@ -114,24 +114,22 @@ func GetDashboard(c *m.ReqContext) Response {
return Json(200, dto) return Json(200, dto)
} }
func getUserLogin(userId int64) string { func getUserLogin(userID int64) string {
query := m.GetUserByIdQuery{Id: userId} query := m.GetUserByIdQuery{Id: userID}
err := bus.Dispatch(&query) err := bus.Dispatch(&query)
if err != nil { if err != nil {
return "Anonymous" return "Anonymous"
} else {
user := query.Result
return user.Login
} }
return query.Result.Login
} }
func getDashboardHelper(orgId int64, slug string, id int64, uid string) (*m.Dashboard, Response) { func getDashboardHelper(orgID int64, slug string, id int64, uid string) (*m.Dashboard, Response) {
var query m.GetDashboardQuery var query m.GetDashboardQuery
if len(uid) > 0 { if len(uid) > 0 {
query = m.GetDashboardQuery{Uid: uid, Id: id, OrgId: orgId} query = m.GetDashboardQuery{Uid: uid, Id: id, OrgId: orgID}
} else { } else {
query = m.GetDashboardQuery{Slug: slug, Id: id, OrgId: orgId} query = m.GetDashboardQuery{Slug: slug, Id: id, OrgId: orgID}
} }
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
...@@ -173,7 +171,7 @@ func DeleteDashboard(c *m.ReqContext) Response { ...@@ -173,7 +171,7 @@ func DeleteDashboard(c *m.ReqContext) Response {
}) })
} }
func DeleteDashboardByUid(c *m.ReqContext) Response { func DeleteDashboardByUID(c *m.ReqContext) Response {
dash, rsp := getDashboardHelper(c.OrgId, "", 0, c.Params(":uid")) dash, rsp := getDashboardHelper(c.OrgId, "", 0, c.Params(":uid"))
if rsp != nil { if rsp != nil {
return rsp return rsp
...@@ -291,9 +289,8 @@ func GetHomeDashboard(c *m.ReqContext) Response { ...@@ -291,9 +289,8 @@ func GetHomeDashboard(c *m.ReqContext) Response {
url := m.GetDashboardUrl(slugQuery.Result.Uid, slugQuery.Result.Slug) url := m.GetDashboardUrl(slugQuery.Result.Uid, slugQuery.Result.Slug)
dashRedirect := dtos.DashboardRedirect{RedirectUri: url} dashRedirect := dtos.DashboardRedirect{RedirectUri: url}
return Json(200, &dashRedirect) return Json(200, &dashRedirect)
} else {
log.Warn("Failed to get slug from database, %s", err.Error())
} }
log.Warn("Failed to get slug from database, %s", err.Error())
} }
filePath := path.Join(setting.StaticRootPath, "dashboards/home.json") filePath := path.Join(setting.StaticRootPath, "dashboards/home.json")
...@@ -339,22 +336,22 @@ func addGettingStartedPanelToHomeDashboard(dash *simplejson.Json) { ...@@ -339,22 +336,22 @@ func addGettingStartedPanelToHomeDashboard(dash *simplejson.Json) {
// GetDashboardVersions returns all dashboard versions as JSON // GetDashboardVersions returns all dashboard versions as JSON
func GetDashboardVersions(c *m.ReqContext) Response { func GetDashboardVersions(c *m.ReqContext) Response {
dashId := c.ParamsInt64(":dashboardId") dashID := c.ParamsInt64(":dashboardId")
guardian := guardian.New(dashId, c.OrgId, c.SignedInUser) guardian := guardian.New(dashID, c.OrgId, c.SignedInUser)
if canSave, err := guardian.CanSave(); err != nil || !canSave { if canSave, err := guardian.CanSave(); err != nil || !canSave {
return dashboardGuardianResponse(err) return dashboardGuardianResponse(err)
} }
query := m.GetDashboardVersionsQuery{ query := m.GetDashboardVersionsQuery{
OrgId: c.OrgId, OrgId: c.OrgId,
DashboardId: dashId, DashboardId: dashID,
Limit: c.QueryInt("limit"), Limit: c.QueryInt("limit"),
Start: c.QueryInt("start"), Start: c.QueryInt("start"),
} }
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
return ApiError(404, fmt.Sprintf("No versions found for dashboardId %d", dashId), err) return ApiError(404, fmt.Sprintf("No versions found for dashboardId %d", dashID), err)
} }
for _, version := range query.Result { for _, version := range query.Result {
...@@ -378,21 +375,21 @@ func GetDashboardVersions(c *m.ReqContext) Response { ...@@ -378,21 +375,21 @@ func GetDashboardVersions(c *m.ReqContext) Response {
// GetDashboardVersion returns the dashboard version with the given ID. // GetDashboardVersion returns the dashboard version with the given ID.
func GetDashboardVersion(c *m.ReqContext) Response { func GetDashboardVersion(c *m.ReqContext) Response {
dashId := c.ParamsInt64(":dashboardId") dashID := c.ParamsInt64(":dashboardId")
guardian := guardian.New(dashId, c.OrgId, c.SignedInUser) guardian := guardian.New(dashID, c.OrgId, c.SignedInUser)
if canSave, err := guardian.CanSave(); err != nil || !canSave { if canSave, err := guardian.CanSave(); err != nil || !canSave {
return dashboardGuardianResponse(err) return dashboardGuardianResponse(err)
} }
query := m.GetDashboardVersionQuery{ query := m.GetDashboardVersionQuery{
OrgId: c.OrgId, OrgId: c.OrgId,
DashboardId: dashId, DashboardId: dashID,
Version: c.ParamsInt(":id"), Version: c.ParamsInt(":id"),
} }
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
return ApiError(500, fmt.Sprintf("Dashboard version %d not found for dashboardId %d", query.Version, dashId), err) return ApiError(500, fmt.Sprintf("Dashboard version %d not found for dashboardId %d", query.Version, dashID), err)
} }
creator := "Anonymous" creator := "Anonymous"
......
...@@ -10,14 +10,14 @@ import ( ...@@ -10,14 +10,14 @@ import (
) )
func GetDashboardPermissionList(c *m.ReqContext) Response { func GetDashboardPermissionList(c *m.ReqContext) Response {
dashId := c.ParamsInt64(":dashboardId") dashID := c.ParamsInt64(":dashboardId")
_, rsp := getDashboardHelper(c.OrgId, "", dashId, "") _, rsp := getDashboardHelper(c.OrgId, "", dashID, "")
if rsp != nil { if rsp != nil {
return rsp return rsp
} }
g := guardian.New(dashId, c.OrgId, c.SignedInUser) g := guardian.New(dashID, c.OrgId, c.SignedInUser)
if canAdmin, err := g.CanAdmin(); err != nil || !canAdmin { if canAdmin, err := g.CanAdmin(); err != nil || !canAdmin {
return dashboardGuardianResponse(err) return dashboardGuardianResponse(err)
...@@ -38,25 +38,25 @@ func GetDashboardPermissionList(c *m.ReqContext) Response { ...@@ -38,25 +38,25 @@ func GetDashboardPermissionList(c *m.ReqContext) Response {
} }
func UpdateDashboardPermissions(c *m.ReqContext, apiCmd dtos.UpdateDashboardAclCommand) Response { func UpdateDashboardPermissions(c *m.ReqContext, apiCmd dtos.UpdateDashboardAclCommand) Response {
dashId := c.ParamsInt64(":dashboardId") dashID := c.ParamsInt64(":dashboardId")
_, rsp := getDashboardHelper(c.OrgId, "", dashId, "") _, rsp := getDashboardHelper(c.OrgId, "", dashID, "")
if rsp != nil { if rsp != nil {
return rsp return rsp
} }
g := guardian.New(dashId, c.OrgId, c.SignedInUser) g := guardian.New(dashID, c.OrgId, c.SignedInUser)
if canAdmin, err := g.CanAdmin(); err != nil || !canAdmin { if canAdmin, err := g.CanAdmin(); err != nil || !canAdmin {
return dashboardGuardianResponse(err) return dashboardGuardianResponse(err)
} }
cmd := m.UpdateDashboardAclCommand{} cmd := m.UpdateDashboardAclCommand{}
cmd.DashboardId = dashId cmd.DashboardId = dashID
for _, item := range apiCmd.Items { for _, item := range apiCmd.Items {
cmd.Items = append(cmd.Items, &m.DashboardAcl{ cmd.Items = append(cmd.Items, &m.DashboardAcl{
OrgId: c.OrgId, OrgId: c.OrgId,
DashboardId: dashId, DashboardId: dashID,
UserId: item.UserId, UserId: item.UserId,
TeamId: item.TeamId, TeamId: item.TeamId,
Role: item.Role, Role: item.Role,
......
...@@ -106,9 +106,9 @@ func DeleteDashboardSnapshot(c *m.ReqContext) Response { ...@@ -106,9 +106,9 @@ func DeleteDashboardSnapshot(c *m.ReqContext) Response {
return ApiError(404, "Failed to get dashboard snapshot", nil) return ApiError(404, "Failed to get dashboard snapshot", nil)
} }
dashboard := query.Result.Dashboard dashboard := query.Result.Dashboard
dashboardId := dashboard.Get("id").MustInt64() dashboardID := dashboard.Get("id").MustInt64()
guardian := guardian.New(dashboardId, c.OrgId, c.SignedInUser) guardian := guardian.New(dashboardID, c.OrgId, c.SignedInUser)
canEdit, err := guardian.CanEdit() canEdit, err := guardian.CanEdit()
if err != nil { if err != nil {
return ApiError(500, "Error while checking permissions for snapshot", err) return ApiError(500, "Error while checking permissions for snapshot", err)
......
...@@ -105,7 +105,7 @@ func TestDashboardApiEndpoint(t *testing.T) { ...@@ -105,7 +105,7 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) { loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
CallDeleteDashboardByUid(sc) CallDeleteDashboardByUID(sc)
So(sc.resp.Code, ShouldEqual, 403) So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by uid", func() { Convey("Should lookup dashboard by uid", func() {
...@@ -165,7 +165,7 @@ func TestDashboardApiEndpoint(t *testing.T) { ...@@ -165,7 +165,7 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) { loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
CallDeleteDashboardByUid(sc) CallDeleteDashboardByUID(sc)
So(sc.resp.Code, ShouldEqual, 200) So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by uid", func() { Convey("Should lookup dashboard by uid", func() {
...@@ -271,7 +271,7 @@ func TestDashboardApiEndpoint(t *testing.T) { ...@@ -271,7 +271,7 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) { loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
CallDeleteDashboardByUid(sc) CallDeleteDashboardByUID(sc)
So(sc.resp.Code, ShouldEqual, 403) So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by uid", func() { Convey("Should lookup dashboard by uid", func() {
...@@ -329,7 +329,7 @@ func TestDashboardApiEndpoint(t *testing.T) { ...@@ -329,7 +329,7 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) { loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
CallDeleteDashboardByUid(sc) CallDeleteDashboardByUID(sc)
So(sc.resp.Code, ShouldEqual, 403) So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by uid", func() { Convey("Should lookup dashboard by uid", func() {
...@@ -398,7 +398,7 @@ func TestDashboardApiEndpoint(t *testing.T) { ...@@ -398,7 +398,7 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) { loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
CallDeleteDashboardByUid(sc) CallDeleteDashboardByUID(sc)
So(sc.resp.Code, ShouldEqual, 200) So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by uid", func() { Convey("Should lookup dashboard by uid", func() {
...@@ -468,7 +468,7 @@ func TestDashboardApiEndpoint(t *testing.T) { ...@@ -468,7 +468,7 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) { loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
CallDeleteDashboardByUid(sc) CallDeleteDashboardByUID(sc)
So(sc.resp.Code, ShouldEqual, 403) So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by uid", func() { Convey("Should lookup dashboard by uid", func() {
...@@ -527,7 +527,7 @@ func TestDashboardApiEndpoint(t *testing.T) { ...@@ -527,7 +527,7 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) { loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
CallDeleteDashboardByUid(sc) CallDeleteDashboardByUID(sc)
So(sc.resp.Code, ShouldEqual, 200) So(sc.resp.Code, ShouldEqual, 200)
Convey("Should lookup dashboard by uid", func() { Convey("Should lookup dashboard by uid", func() {
...@@ -594,7 +594,7 @@ func TestDashboardApiEndpoint(t *testing.T) { ...@@ -594,7 +594,7 @@ func TestDashboardApiEndpoint(t *testing.T) {
}) })
loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) { loggedInUserScenarioWithRole("When calling DELETE on", "DELETE", "/api/dashboards/uid/abcdefghi", "/api/dashboards/uid/:uid", role, func(sc *scenarioContext) {
CallDeleteDashboardByUid(sc) CallDeleteDashboardByUID(sc)
So(sc.resp.Code, ShouldEqual, 403) So(sc.resp.Code, ShouldEqual, 403)
Convey("Should lookup dashboard by uid", func() { Convey("Should lookup dashboard by uid", func() {
...@@ -837,12 +837,12 @@ func CallDeleteDashboard(sc *scenarioContext) { ...@@ -837,12 +837,12 @@ func CallDeleteDashboard(sc *scenarioContext) {
sc.fakeReqWithParams("DELETE", sc.url, map[string]string{}).exec() sc.fakeReqWithParams("DELETE", sc.url, map[string]string{}).exec()
} }
func CallDeleteDashboardByUid(sc *scenarioContext) { func CallDeleteDashboardByUID(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *m.DeleteDashboardCommand) error { bus.AddHandler("test", func(cmd *m.DeleteDashboardCommand) error {
return nil return nil
}) })
sc.handlerFunc = DeleteDashboardByUid sc.handlerFunc = DeleteDashboardByUID
sc.fakeReqWithParams("DELETE", sc.url, map[string]string{}).exec() sc.fakeReqWithParams("DELETE", sc.url, map[string]string{}).exec()
} }
......
...@@ -13,19 +13,19 @@ import ( ...@@ -13,19 +13,19 @@ import (
const HeaderNameNoBackendCache = "X-Grafana-NoCache" const HeaderNameNoBackendCache = "X-Grafana-NoCache"
func (hs *HttpServer) getDatasourceById(id int64, orgId int64, nocache bool) (*m.DataSource, error) { func (hs *HttpServer) getDatasourceByID(id int64, orgID int64, nocache bool) (*m.DataSource, error) {
cacheKey := fmt.Sprintf("ds-%d", id) cacheKey := fmt.Sprintf("ds-%d", id)
if !nocache { if !nocache {
if cached, found := hs.cache.Get(cacheKey); found { if cached, found := hs.cache.Get(cacheKey); found {
ds := cached.(*m.DataSource) ds := cached.(*m.DataSource)
if ds.OrgId == orgId { if ds.OrgId == orgID {
return ds, nil return ds, nil
} }
} }
} }
query := m.GetDataSourceByIdQuery{Id: id, OrgId: orgId} query := m.GetDataSourceByIdQuery{Id: id, OrgId: orgID}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
return nil, err return nil, err
} }
...@@ -39,7 +39,7 @@ func (hs *HttpServer) ProxyDataSourceRequest(c *m.ReqContext) { ...@@ -39,7 +39,7 @@ func (hs *HttpServer) ProxyDataSourceRequest(c *m.ReqContext) {
nocache := c.Req.Header.Get(HeaderNameNoBackendCache) == "true" nocache := c.Req.Header.Get(HeaderNameNoBackendCache) == "true"
ds, err := hs.getDatasourceById(c.ParamsInt64(":id"), c.OrgId, nocache) ds, err := hs.getDatasourceByID(c.ParamsInt64(":id"), c.OrgId, nocache)
if err != nil { if err != nil {
c.JsonApiErr(500, "Unable to load datasource meta data", err) c.JsonApiErr(500, "Unable to load datasource meta data", err)
......
...@@ -49,7 +49,7 @@ func GetDataSources(c *m.ReqContext) Response { ...@@ -49,7 +49,7 @@ func GetDataSources(c *m.ReqContext) Response {
return Json(200, &result) return Json(200, &result)
} }
func GetDataSourceById(c *m.ReqContext) Response { func GetDataSourceByID(c *m.ReqContext) Response {
query := m.GetDataSourceByIdQuery{ query := m.GetDataSourceByIdQuery{
Id: c.ParamsInt64(":id"), Id: c.ParamsInt64(":id"),
OrgId: c.OrgId, OrgId: c.OrgId,
...@@ -68,14 +68,14 @@ func GetDataSourceById(c *m.ReqContext) Response { ...@@ -68,14 +68,14 @@ func GetDataSourceById(c *m.ReqContext) Response {
return Json(200, &dtos) return Json(200, &dtos)
} }
func DeleteDataSourceById(c *m.ReqContext) Response { func DeleteDataSourceByID(c *m.ReqContext) Response {
id := c.ParamsInt64(":id") id := c.ParamsInt64(":id")
if id <= 0 { if id <= 0 {
return ApiError(400, "Missing valid datasource id", nil) return ApiError(400, "Missing valid datasource id", nil)
} }
ds, err := getRawDataSourceById(id, c.OrgId) ds, err := getRawDataSourceByID(id, c.OrgId)
if err != nil { if err != nil {
return ApiError(400, "Failed to delete datasource", nil) return ApiError(400, "Failed to delete datasource", nil)
} }
...@@ -143,7 +143,7 @@ func UpdateDataSource(c *m.ReqContext, cmd m.UpdateDataSourceCommand) Response { ...@@ -143,7 +143,7 @@ func UpdateDataSource(c *m.ReqContext, cmd m.UpdateDataSourceCommand) Response {
cmd.OrgId = c.OrgId cmd.OrgId = c.OrgId
cmd.Id = c.ParamsInt64(":id") cmd.Id = c.ParamsInt64(":id")
err := fillWithSecureJsonData(&cmd) err := fillWithSecureJSONData(&cmd)
if err != nil { if err != nil {
return ApiError(500, "Failed to update datasource", err) return ApiError(500, "Failed to update datasource", err)
} }
...@@ -152,9 +152,8 @@ func UpdateDataSource(c *m.ReqContext, cmd m.UpdateDataSourceCommand) Response { ...@@ -152,9 +152,8 @@ func UpdateDataSource(c *m.ReqContext, cmd m.UpdateDataSourceCommand) Response {
if err != nil { if err != nil {
if err == m.ErrDataSourceUpdatingOldVersion { if err == m.ErrDataSourceUpdatingOldVersion {
return ApiError(500, "Failed to update datasource. Reload new version and try again", err) return ApiError(500, "Failed to update datasource. Reload new version and try again", err)
} else {
return ApiError(500, "Failed to update datasource", err)
} }
return ApiError(500, "Failed to update datasource", err)
} }
ds := convertModelToDtos(cmd.Result) ds := convertModelToDtos(cmd.Result)
return Json(200, util.DynMap{ return Json(200, util.DynMap{
...@@ -165,12 +164,12 @@ func UpdateDataSource(c *m.ReqContext, cmd m.UpdateDataSourceCommand) Response { ...@@ -165,12 +164,12 @@ func UpdateDataSource(c *m.ReqContext, cmd m.UpdateDataSourceCommand) Response {
}) })
} }
func fillWithSecureJsonData(cmd *m.UpdateDataSourceCommand) error { func fillWithSecureJSONData(cmd *m.UpdateDataSourceCommand) error {
if len(cmd.SecureJsonData) == 0 { if len(cmd.SecureJsonData) == 0 {
return nil return nil
} }
ds, err := getRawDataSourceById(cmd.Id, cmd.OrgId) ds, err := getRawDataSourceByID(cmd.Id, cmd.OrgId)
if err != nil { if err != nil {
return err return err
} }
...@@ -179,8 +178,8 @@ func fillWithSecureJsonData(cmd *m.UpdateDataSourceCommand) error { ...@@ -179,8 +178,8 @@ func fillWithSecureJsonData(cmd *m.UpdateDataSourceCommand) error {
return m.ErrDatasourceIsReadOnly return m.ErrDatasourceIsReadOnly
} }
secureJsonData := ds.SecureJsonData.Decrypt() secureJSONData := ds.SecureJsonData.Decrypt()
for k, v := range secureJsonData { for k, v := range secureJSONData {
if _, ok := cmd.SecureJsonData[k]; !ok { if _, ok := cmd.SecureJsonData[k]; !ok {
cmd.SecureJsonData[k] = v cmd.SecureJsonData[k] = v
...@@ -190,10 +189,10 @@ func fillWithSecureJsonData(cmd *m.UpdateDataSourceCommand) error { ...@@ -190,10 +189,10 @@ func fillWithSecureJsonData(cmd *m.UpdateDataSourceCommand) error {
return nil return nil
} }
func getRawDataSourceById(id int64, orgId int64) (*m.DataSource, error) { func getRawDataSourceByID(id int64, orgID int64) (*m.DataSource, error) {
query := m.GetDataSourceByIdQuery{ query := m.GetDataSourceByIdQuery{
Id: id, Id: id,
OrgId: orgId, OrgId: orgID,
} }
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
...@@ -220,7 +219,7 @@ func GetDataSourceByName(c *m.ReqContext) Response { ...@@ -220,7 +219,7 @@ func GetDataSourceByName(c *m.ReqContext) Response {
} }
// Get /api/datasources/id/:name // Get /api/datasources/id/:name
func GetDataSourceIdByName(c *m.ReqContext) Response { func GetDataSourceIDByName(c *m.ReqContext) Response {
query := m.GetDataSourceByNameQuery{Name: c.Params(":name"), OrgId: c.OrgId} query := m.GetDataSourceByNameQuery{Name: c.Params(":name"), OrgId: c.OrgId}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
......
...@@ -31,7 +31,7 @@ func GetFolders(c *m.ReqContext) Response { ...@@ -31,7 +31,7 @@ func GetFolders(c *m.ReqContext) Response {
return Json(200, result) return Json(200, result)
} }
func GetFolderByUid(c *m.ReqContext) Response { func GetFolderByUID(c *m.ReqContext) Response {
s := dashboards.NewFolderService(c.OrgId, c.SignedInUser) s := dashboards.NewFolderService(c.OrgId, c.SignedInUser)
folder, err := s.GetFolderByUid(c.Params(":uid")) folder, err := s.GetFolderByUid(c.Params(":uid"))
...@@ -43,7 +43,7 @@ func GetFolderByUid(c *m.ReqContext) Response { ...@@ -43,7 +43,7 @@ func GetFolderByUid(c *m.ReqContext) Response {
return Json(200, toFolderDto(g, folder)) return Json(200, toFolderDto(g, folder))
} }
func GetFolderById(c *m.ReqContext) Response { func GetFolderByID(c *m.ReqContext) Response {
s := dashboards.NewFolderService(c.OrgId, c.SignedInUser) s := dashboards.NewFolderService(c.OrgId, c.SignedInUser)
folder, err := s.GetFolderById(c.ParamsInt64(":id")) folder, err := s.GetFolderById(c.ParamsInt64(":id"))
if err != nil { if err != nil {
......
...@@ -133,8 +133,8 @@ func TestFoldersApiEndpoint(t *testing.T) { ...@@ -133,8 +133,8 @@ func TestFoldersApiEndpoint(t *testing.T) {
}) })
} }
func callGetFolderByUid(sc *scenarioContext) { func callGetFolderByUID(sc *scenarioContext) {
sc.handlerFunc = GetFolderByUid sc.handlerFunc = GetFolderByUID
sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec() sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec()
} }
......
...@@ -39,7 +39,7 @@ type HttpServer struct { ...@@ -39,7 +39,7 @@ type HttpServer struct {
httpSrv *http.Server httpSrv *http.Server
} }
func NewHttpServer() *HttpServer { func NewHTTPServer() *HttpServer {
return &HttpServer{ return &HttpServer{
log: log.New("http.server"), log: log.New("http.server"),
cache: gocache.New(5*time.Minute, 10*time.Minute), cache: gocache.New(5*time.Minute, 10*time.Minute),
......
...@@ -32,13 +32,13 @@ func setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, error) { ...@@ -32,13 +32,13 @@ func setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, error) {
locale = parts[0] locale = parts[0]
} }
appUrl := setting.AppUrl appURL := setting.AppUrl
appSubUrl := setting.AppSubUrl appSubURL := setting.AppSubUrl
// special case when doing localhost call from phantomjs // special case when doing localhost call from phantomjs
if c.IsRenderCall { if c.IsRenderCall {
appUrl = fmt.Sprintf("%s://localhost:%s", setting.Protocol, setting.HttpPort) appURL = fmt.Sprintf("%s://localhost:%s", setting.Protocol, setting.HttpPort)
appSubUrl = "" appSubURL = ""
settings["appSubUrl"] = "" settings["appSubUrl"] = ""
} }
...@@ -62,8 +62,8 @@ func setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, error) { ...@@ -62,8 +62,8 @@ func setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, error) {
}, },
Settings: settings, Settings: settings,
Theme: prefs.Theme, Theme: prefs.Theme,
AppUrl: appUrl, AppUrl: appURL,
AppSubUrl: appSubUrl, AppSubUrl: appSubURL,
GoogleAnalyticsId: setting.GoogleAnalyticsId, GoogleAnalyticsId: setting.GoogleAnalyticsId,
GoogleTagManagerId: setting.GoogleTagManagerId, GoogleTagManagerId: setting.GoogleTagManagerId,
BuildVersion: setting.BuildVersion, BuildVersion: setting.BuildVersion,
...@@ -80,8 +80,8 @@ func setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, error) { ...@@ -80,8 +80,8 @@ func setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, error) {
data.User.Name = data.User.Login data.User.Name = data.User.Login
} }
themeUrlParam := c.Query("theme") themeURLParam := c.Query("theme")
if themeUrlParam == "light" { if themeURLParam == "light" {
data.User.LightTheme = true data.User.LightTheme = true
data.Theme = "light" data.Theme = "light"
} }
...@@ -299,12 +299,12 @@ func setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, error) { ...@@ -299,12 +299,12 @@ func setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, error) {
} }
func Index(c *m.ReqContext) { func Index(c *m.ReqContext) {
if data, err := setIndexViewData(c); err != nil { data, err := setIndexViewData(c)
if err != nil {
c.Handle(500, "Failed to get settings", err) c.Handle(500, "Failed to get settings", err)
return return
} else {
c.HTML(200, "index", data)
} }
c.HTML(200, "index", data)
} }
func NotFoundHandler(c *m.ReqContext) { func NotFoundHandler(c *m.ReqContext) {
...@@ -313,10 +313,11 @@ func NotFoundHandler(c *m.ReqContext) { ...@@ -313,10 +313,11 @@ func NotFoundHandler(c *m.ReqContext) {
return return
} }
if data, err := setIndexViewData(c); err != nil { data, err := setIndexViewData(c)
if err != nil {
c.Handle(500, "Failed to get settings", err) c.Handle(500, "Failed to get settings", err)
return return
} else {
c.HTML(404, "index", data)
} }
c.HTML(404, "index", data)
} }
...@@ -14,7 +14,7 @@ import ( ...@@ -14,7 +14,7 @@ import (
) )
const ( const (
VIEW_INDEX = "index" ViewIndex = "index"
) )
func LoginView(c *m.ReqContext) { func LoginView(c *m.ReqContext) {
...@@ -40,7 +40,7 @@ func LoginView(c *m.ReqContext) { ...@@ -40,7 +40,7 @@ func LoginView(c *m.ReqContext) {
} }
if !tryLoginUsingRememberCookie(c) { if !tryLoginUsingRememberCookie(c) {
c.HTML(200, VIEW_INDEX, viewData) c.HTML(200, ViewIndex, viewData)
return return
} }
...@@ -87,7 +87,7 @@ func tryLoginUsingRememberCookie(c *m.ReqContext) bool { ...@@ -87,7 +87,7 @@ func tryLoginUsingRememberCookie(c *m.ReqContext) bool {
return true return true
} }
func LoginApiPing(c *m.ReqContext) { func LoginAPIPing(c *m.ReqContext) {
if !tryLoginUsingRememberCookie(c) { if !tryLoginUsingRememberCookie(c) {
c.JsonApiErr(401, "Unauthorized", nil) c.JsonApiErr(401, "Unauthorized", nil)
return return
......
...@@ -20,12 +20,12 @@ func QueryMetrics(c *m.ReqContext, reqDto dtos.MetricRequest) Response { ...@@ -20,12 +20,12 @@ func QueryMetrics(c *m.ReqContext, reqDto dtos.MetricRequest) Response {
return ApiError(400, "No queries found in query", nil) return ApiError(400, "No queries found in query", nil)
} }
dsId, err := reqDto.Queries[0].Get("datasourceId").Int64() dsID, err := reqDto.Queries[0].Get("datasourceId").Int64()
if err != nil { if err != nil {
return ApiError(400, "Query missing datasourceId", nil) return ApiError(400, "Query missing datasourceId", nil)
} }
dsQuery := m.GetDataSourceByIdQuery{Id: dsId, OrgId: c.OrgId} dsQuery := m.GetDataSourceByIdQuery{Id: dsID, OrgId: c.OrgId}
if err := bus.Dispatch(&dsQuery); err != nil { if err := bus.Dispatch(&dsQuery); err != nil {
return ApiError(500, "failed to fetch data source", err) return ApiError(500, "failed to fetch data source", err)
} }
...@@ -82,7 +82,7 @@ func GenerateError(c *m.ReqContext) Response { ...@@ -82,7 +82,7 @@ func GenerateError(c *m.ReqContext) Response {
} }
// GET /api/tsdb/testdata/gensql // GET /api/tsdb/testdata/gensql
func GenerateSqlTestData(c *m.ReqContext) Response { func GenerateSQLTestData(c *m.ReqContext) Response {
if err := bus.Dispatch(&m.InsertSqlTestDataCommand{}); err != nil { if err := bus.Dispatch(&m.InsertSqlTestDataCommand{}); err != nil {
return ApiError(500, "Failed to insert test data", err) return ApiError(500, "Failed to insert test data", err)
} }
......
...@@ -15,7 +15,7 @@ func GetOrgCurrent(c *m.ReqContext) Response { ...@@ -15,7 +15,7 @@ func GetOrgCurrent(c *m.ReqContext) Response {
} }
// GET /api/orgs/:orgId // GET /api/orgs/:orgId
func GetOrgById(c *m.ReqContext) Response { func GetOrgByID(c *m.ReqContext) Response {
return getOrgHelper(c.ParamsInt64(":orgId")) return getOrgHelper(c.ParamsInt64(":orgId"))
} }
...@@ -106,8 +106,8 @@ func UpdateOrg(c *m.ReqContext, form dtos.UpdateOrgForm) Response { ...@@ -106,8 +106,8 @@ func UpdateOrg(c *m.ReqContext, form dtos.UpdateOrgForm) Response {
return updateOrgHelper(form, c.ParamsInt64(":orgId")) return updateOrgHelper(form, c.ParamsInt64(":orgId"))
} }
func updateOrgHelper(form dtos.UpdateOrgForm, orgId int64) Response { func updateOrgHelper(form dtos.UpdateOrgForm, orgID int64) Response {
cmd := m.UpdateOrgCommand{Name: form.Name, OrgId: orgId} cmd := m.UpdateOrgCommand{Name: form.Name, OrgId: orgID}
if err := bus.Dispatch(&cmd); err != nil { if err := bus.Dispatch(&cmd); err != nil {
if err == m.ErrOrgNameTaken { if err == m.ErrOrgNameTaken {
return ApiError(400, "Organization name taken", err) return ApiError(400, "Organization name taken", err)
...@@ -128,9 +128,9 @@ func UpdateOrgAddress(c *m.ReqContext, form dtos.UpdateOrgAddressForm) Response ...@@ -128,9 +128,9 @@ func UpdateOrgAddress(c *m.ReqContext, form dtos.UpdateOrgAddressForm) Response
return updateOrgAddressHelper(form, c.ParamsInt64(":orgId")) return updateOrgAddressHelper(form, c.ParamsInt64(":orgId"))
} }
func updateOrgAddressHelper(form dtos.UpdateOrgAddressForm, orgId int64) Response { func updateOrgAddressHelper(form dtos.UpdateOrgAddressForm, orgID int64) Response {
cmd := m.UpdateOrgAddressCommand{ cmd := m.UpdateOrgAddressCommand{
OrgId: orgId, OrgId: orgID,
Address: m.Address{ Address: m.Address{
Address1: form.Address1, Address1: form.Address1,
Address2: form.Address2, Address2: form.Address2,
...@@ -149,7 +149,7 @@ func updateOrgAddressHelper(form dtos.UpdateOrgAddressForm, orgId int64) Respons ...@@ -149,7 +149,7 @@ func updateOrgAddressHelper(form dtos.UpdateOrgAddressForm, orgId int64) Respons
} }
// GET /api/orgs/:orgId // GET /api/orgs/:orgId
func DeleteOrgById(c *m.ReqContext) Response { func DeleteOrgByID(c *m.ReqContext) Response {
if err := bus.Dispatch(&m.DeleteOrgCommand{Id: c.ParamsInt64(":orgId")}); err != nil { if err := bus.Dispatch(&m.DeleteOrgCommand{Id: c.ParamsInt64(":orgId")}); err != nil {
if err == m.ErrOrgNotFound { if err == m.ErrOrgNotFound {
return ApiError(404, "Failed to delete organization. ID not found", nil) return ApiError(404, "Failed to delete organization. ID not found", nil)
......
...@@ -96,7 +96,7 @@ func inviteExistingUserToOrg(c *m.ReqContext, user *m.User, inviteDto *dtos.AddI ...@@ -96,7 +96,7 @@ func inviteExistingUserToOrg(c *m.ReqContext, user *m.User, inviteDto *dtos.AddI
return ApiError(412, fmt.Sprintf("User %s is already added to organization", inviteDto.LoginOrEmail), err) return ApiError(412, fmt.Sprintf("User %s is already added to organization", inviteDto.LoginOrEmail), err)
} }
return ApiError(500, "Error while trying to create org user", err) return ApiError(500, "Error while trying to create org user", err)
} else { }
if inviteDto.SendEmail && util.IsEmail(user.Email) { if inviteDto.SendEmail && util.IsEmail(user.Email) {
emailCmd := m.SendEmailCommand{ emailCmd := m.SendEmailCommand{
...@@ -115,7 +115,6 @@ func inviteExistingUserToOrg(c *m.ReqContext, user *m.User, inviteDto *dtos.AddI ...@@ -115,7 +115,6 @@ func inviteExistingUserToOrg(c *m.ReqContext, user *m.User, inviteDto *dtos.AddI
} }
return ApiSuccess(fmt.Sprintf("Existing Grafana user %s added to org %s", user.NameOrFallback(), c.OrgName)) return ApiSuccess(fmt.Sprintf("Existing Grafana user %s added to org %s", user.NameOrFallback(), c.OrgName))
}
} }
func RevokeInvite(c *m.ReqContext) Response { func RevokeInvite(c *m.ReqContext) Response {
......
...@@ -53,9 +53,9 @@ func GetOrgUsers(c *m.ReqContext) Response { ...@@ -53,9 +53,9 @@ func GetOrgUsers(c *m.ReqContext) Response {
return getOrgUsersHelper(c.ParamsInt64(":orgId"), "", 0) return getOrgUsersHelper(c.ParamsInt64(":orgId"), "", 0)
} }
func getOrgUsersHelper(orgId int64, query string, limit int) Response { func getOrgUsersHelper(orgID int64, query string, limit int) Response {
q := m.GetOrgUsersQuery{ q := m.GetOrgUsersQuery{
OrgId: orgId, OrgId: orgID,
Query: query, Query: query,
Limit: limit, Limit: limit,
} }
...@@ -102,19 +102,19 @@ func updateOrgUserHelper(cmd m.UpdateOrgUserCommand) Response { ...@@ -102,19 +102,19 @@ func updateOrgUserHelper(cmd m.UpdateOrgUserCommand) Response {
// DELETE /api/org/users/:userId // DELETE /api/org/users/:userId
func RemoveOrgUserForCurrentOrg(c *m.ReqContext) Response { func RemoveOrgUserForCurrentOrg(c *m.ReqContext) Response {
userId := c.ParamsInt64(":userId") userID := c.ParamsInt64(":userId")
return removeOrgUserHelper(c.OrgId, userId) return removeOrgUserHelper(c.OrgId, userID)
} }
// DELETE /api/orgs/:orgId/users/:userId // DELETE /api/orgs/:orgId/users/:userId
func RemoveOrgUser(c *m.ReqContext) Response { func RemoveOrgUser(c *m.ReqContext) Response {
userId := c.ParamsInt64(":userId") userID := c.ParamsInt64(":userId")
orgId := c.ParamsInt64(":orgId") orgID := c.ParamsInt64(":orgId")
return removeOrgUserHelper(orgId, userId) return removeOrgUserHelper(orgID, userID)
} }
func removeOrgUserHelper(orgId int64, userId int64) Response { func removeOrgUserHelper(orgID int64, userID int64) Response {
cmd := m.RemoveOrgUserCommand{OrgId: orgId, UserId: userId} cmd := m.RemoveOrgUserCommand{OrgId: orgID, UserId: userID}
if err := bus.Dispatch(&cmd); err != nil { if err := bus.Dispatch(&cmd); err != nil {
if err == m.ErrLastOrgAdmin { if err == m.ErrLastOrgAdmin {
......
...@@ -127,9 +127,9 @@ func GetPlaylistItems(c *m.ReqContext) Response { ...@@ -127,9 +127,9 @@ func GetPlaylistItems(c *m.ReqContext) Response {
} }
func GetPlaylistDashboards(c *m.ReqContext) Response { func GetPlaylistDashboards(c *m.ReqContext) Response {
playlistId := c.ParamsInt64(":id") playlistID := c.ParamsInt64(":id")
playlists, err := LoadPlaylistDashboards(c.OrgId, c.SignedInUser, playlistId) playlists, err := LoadPlaylistDashboards(c.OrgId, c.SignedInUser, playlistID)
if err != nil { if err != nil {
return ApiError(500, "Could not load dashboards", err) return ApiError(500, "Could not load dashboards", err)
} }
......
...@@ -34,10 +34,9 @@ func populateDashboardsById(dashboardByIds []int64, dashboardIdOrder map[int64]i ...@@ -34,10 +34,9 @@ func populateDashboardsById(dashboardByIds []int64, dashboardIdOrder map[int64]i
return result, nil return result, nil
} }
func populateDashboardsByTag(orgId int64, signedInUser *m.SignedInUser, dashboardByTag []string, dashboardTagOrder map[string]int) dtos.PlaylistDashboardsSlice { func populateDashboardsByTag(orgID int64, signedInUser *m.SignedInUser, dashboardByTag []string, dashboardTagOrder map[string]int) dtos.PlaylistDashboardsSlice {
result := make(dtos.PlaylistDashboardsSlice, 0) result := make(dtos.PlaylistDashboardsSlice, 0)
if len(dashboardByTag) > 0 {
for _, tag := range dashboardByTag { for _, tag := range dashboardByTag {
searchQuery := search.Query{ searchQuery := search.Query{
Title: "", Title: "",
...@@ -45,7 +44,7 @@ func populateDashboardsByTag(orgId int64, signedInUser *m.SignedInUser, dashboar ...@@ -45,7 +44,7 @@ func populateDashboardsByTag(orgId int64, signedInUser *m.SignedInUser, dashboar
SignedInUser: signedInUser, SignedInUser: signedInUser,
Limit: 100, Limit: 100,
IsStarred: false, IsStarred: false,
OrgId: orgId, OrgId: orgID,
} }
if err := bus.Dispatch(&searchQuery); err == nil { if err := bus.Dispatch(&searchQuery); err == nil {
...@@ -59,24 +58,23 @@ func populateDashboardsByTag(orgId int64, signedInUser *m.SignedInUser, dashboar ...@@ -59,24 +58,23 @@ func populateDashboardsByTag(orgId int64, signedInUser *m.SignedInUser, dashboar
} }
} }
} }
}
return result return result
} }
func LoadPlaylistDashboards(orgId int64, signedInUser *m.SignedInUser, playlistId int64) (dtos.PlaylistDashboardsSlice, error) { func LoadPlaylistDashboards(orgID int64, signedInUser *m.SignedInUser, playlistID int64) (dtos.PlaylistDashboardsSlice, error) {
playlistItems, _ := LoadPlaylistItems(playlistId) playlistItems, _ := LoadPlaylistItems(playlistID)
dashboardByIds := make([]int64, 0) dashboardByIDs := make([]int64, 0)
dashboardByTag := make([]string, 0) dashboardByTag := make([]string, 0)
dashboardIdOrder := make(map[int64]int) dashboardIDOrder := make(map[int64]int)
dashboardTagOrder := make(map[string]int) dashboardTagOrder := make(map[string]int)
for _, i := range playlistItems { for _, i := range playlistItems {
if i.Type == "dashboard_by_id" { if i.Type == "dashboard_by_id" {
dashboardId, _ := strconv.ParseInt(i.Value, 10, 64) dashboardID, _ := strconv.ParseInt(i.Value, 10, 64)
dashboardByIds = append(dashboardByIds, dashboardId) dashboardByIDs = append(dashboardByIDs, dashboardID)
dashboardIdOrder[dashboardId] = i.Order dashboardIDOrder[dashboardID] = i.Order
} }
if i.Type == "dashboard_by_tag" { if i.Type == "dashboard_by_tag" {
...@@ -87,9 +85,9 @@ func LoadPlaylistDashboards(orgId int64, signedInUser *m.SignedInUser, playlistI ...@@ -87,9 +85,9 @@ func LoadPlaylistDashboards(orgId int64, signedInUser *m.SignedInUser, playlistI
result := make(dtos.PlaylistDashboardsSlice, 0) result := make(dtos.PlaylistDashboardsSlice, 0)
var k, _ = populateDashboardsById(dashboardByIds, dashboardIdOrder) var k, _ = populateDashboardsById(dashboardByIDs, dashboardIDOrder)
result = append(result, k...) result = append(result, k...)
result = append(result, populateDashboardsByTag(orgId, signedInUser, dashboardByTag, dashboardTagOrder)...) result = append(result, populateDashboardsByTag(orgID, signedInUser, dashboardByTag, dashboardTagOrder)...)
sort.Sort(result) sort.Sort(result)
return result, nil return result, nil
......
...@@ -78,12 +78,13 @@ func GetPluginList(c *m.ReqContext) Response { ...@@ -78,12 +78,13 @@ func GetPluginList(c *m.ReqContext) Response {
return Json(200, result) return Json(200, result)
} }
func GetPluginSettingById(c *m.ReqContext) Response { func GetPluginSettingByID(c *m.ReqContext) Response {
pluginId := c.Params(":pluginId") pluginID := c.Params(":pluginId")
if def, exists := plugins.Plugins[pluginId]; !exists { def, exists := plugins.Plugins[pluginID]
if !exists {
return ApiError(404, "Plugin not found, no installed plugin with that id", nil) return ApiError(404, "Plugin not found, no installed plugin with that id", nil)
} else { }
dto := &dtos.PluginSetting{ dto := &dtos.PluginSetting{
Type: def.Type, Type: def.Type,
...@@ -100,7 +101,7 @@ func GetPluginSettingById(c *m.ReqContext) Response { ...@@ -100,7 +101,7 @@ func GetPluginSettingById(c *m.ReqContext) Response {
State: def.State, State: def.State,
} }
query := m.GetPluginSettingByIdQuery{PluginId: pluginId, OrgId: c.OrgId} query := m.GetPluginSettingByIdQuery{PluginId: pluginID, OrgId: c.OrgId}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
if err != m.ErrPluginSettingNotFound { if err != m.ErrPluginSettingNotFound {
return ApiError(500, "Failed to get login settings", nil) return ApiError(500, "Failed to get login settings", nil)
...@@ -112,14 +113,13 @@ func GetPluginSettingById(c *m.ReqContext) Response { ...@@ -112,14 +113,13 @@ func GetPluginSettingById(c *m.ReqContext) Response {
} }
return Json(200, dto) return Json(200, dto)
}
} }
func UpdatePluginSetting(c *m.ReqContext, cmd m.UpdatePluginSettingCmd) Response { func UpdatePluginSetting(c *m.ReqContext, cmd m.UpdatePluginSettingCmd) Response {
pluginId := c.Params(":pluginId") pluginID := c.Params(":pluginId")
cmd.OrgId = c.OrgId cmd.OrgId = c.OrgId
cmd.PluginId = pluginId cmd.PluginId = pluginID
if _, ok := plugins.Apps[cmd.PluginId]; !ok { if _, ok := plugins.Apps[cmd.PluginId]; !ok {
return ApiError(404, "Plugin not installed.", nil) return ApiError(404, "Plugin not installed.", nil)
...@@ -133,34 +133,36 @@ func UpdatePluginSetting(c *m.ReqContext, cmd m.UpdatePluginSettingCmd) Response ...@@ -133,34 +133,36 @@ func UpdatePluginSetting(c *m.ReqContext, cmd m.UpdatePluginSettingCmd) Response
} }
func GetPluginDashboards(c *m.ReqContext) Response { func GetPluginDashboards(c *m.ReqContext) Response {
pluginId := c.Params(":pluginId") pluginID := c.Params(":pluginId")
if list, err := plugins.GetPluginDashboards(c.OrgId, pluginId); err != nil { list, err := plugins.GetPluginDashboards(c.OrgId, pluginID)
if err != nil {
if notfound, ok := err.(plugins.PluginNotFoundError); ok { if notfound, ok := err.(plugins.PluginNotFoundError); ok {
return ApiError(404, notfound.Error(), nil) return ApiError(404, notfound.Error(), nil)
} }
return ApiError(500, "Failed to get plugin dashboards", err) return ApiError(500, "Failed to get plugin dashboards", err)
} else {
return Json(200, list)
} }
return Json(200, list)
} }
func GetPluginMarkdown(c *m.ReqContext) Response { func GetPluginMarkdown(c *m.ReqContext) Response {
pluginId := c.Params(":pluginId") pluginID := c.Params(":pluginId")
name := c.Params(":name") name := c.Params(":name")
if content, err := plugins.GetPluginMarkdown(pluginId, name); err != nil { content, err := plugins.GetPluginMarkdown(pluginID, name)
if err != nil {
if notfound, ok := err.(plugins.PluginNotFoundError); ok { if notfound, ok := err.(plugins.PluginNotFoundError); ok {
return ApiError(404, notfound.Error(), nil) return ApiError(404, notfound.Error(), nil)
} }
return ApiError(500, "Could not get markdown file", err) return ApiError(500, "Could not get markdown file", err)
} else { }
resp := Respond(200, content) resp := Respond(200, content)
resp.Header("Content-Type", "text/plain; charset=utf-8") resp.Header("Content-Type", "text/plain; charset=utf-8")
return resp return resp
}
} }
func ImportDashboard(c *m.ReqContext, apiCmd dtos.ImportDashboardCommand) Response { func ImportDashboard(c *m.ReqContext, apiCmd dtos.ImportDashboardCommand) Response {
......
...@@ -24,8 +24,8 @@ func GetUserPreferences(c *m.ReqContext) Response { ...@@ -24,8 +24,8 @@ func GetUserPreferences(c *m.ReqContext) Response {
return getPreferencesFor(c.OrgId, c.UserId) return getPreferencesFor(c.OrgId, c.UserId)
} }
func getPreferencesFor(orgId int64, userId int64) Response { func getPreferencesFor(orgID int64, userID int64) Response {
prefsQuery := m.GetPreferencesQuery{UserId: userId, OrgId: orgId} prefsQuery := m.GetPreferencesQuery{UserId: userID, OrgId: orgID}
if err := bus.Dispatch(&prefsQuery); err != nil { if err := bus.Dispatch(&prefsQuery); err != nil {
return ApiError(500, "Failed to get preferences", err) return ApiError(500, "Failed to get preferences", err)
...@@ -45,10 +45,10 @@ func UpdateUserPreferences(c *m.ReqContext, dtoCmd dtos.UpdatePrefsCmd) Response ...@@ -45,10 +45,10 @@ func UpdateUserPreferences(c *m.ReqContext, dtoCmd dtos.UpdatePrefsCmd) Response
return updatePreferencesFor(c.OrgId, c.UserId, &dtoCmd) return updatePreferencesFor(c.OrgId, c.UserId, &dtoCmd)
} }
func updatePreferencesFor(orgId int64, userId int64, dtoCmd *dtos.UpdatePrefsCmd) Response { func updatePreferencesFor(orgID int64, userID int64, dtoCmd *dtos.UpdatePrefsCmd) Response {
saveCmd := m.SavePreferencesCommand{ saveCmd := m.SavePreferencesCommand{
UserId: userId, UserId: userID,
OrgId: orgId, OrgId: orgID,
Theme: dtoCmd.Theme, Theme: dtoCmd.Theme,
Timezone: dtoCmd.Timezone, Timezone: dtoCmd.Timezone,
HomeDashboardId: dtoCmd.HomeDashboardId, HomeDashboardId: dtoCmd.HomeDashboardId,
......
...@@ -25,19 +25,19 @@ func Search(c *m.ReqContext) { ...@@ -25,19 +25,19 @@ func Search(c *m.ReqContext) {
permission = m.PERMISSION_EDIT permission = m.PERMISSION_EDIT
} }
dbids := make([]int64, 0) dbIDs := make([]int64, 0)
for _, id := range c.QueryStrings("dashboardIds") { for _, id := range c.QueryStrings("dashboardIds") {
dashboardId, err := strconv.ParseInt(id, 10, 64) dashboardID, err := strconv.ParseInt(id, 10, 64)
if err == nil { if err == nil {
dbids = append(dbids, dashboardId) dbIDs = append(dbIDs, dashboardID)
} }
} }
folderIds := make([]int64, 0) folderIDs := make([]int64, 0)
for _, id := range c.QueryStrings("folderIds") { for _, id := range c.QueryStrings("folderIds") {
folderId, err := strconv.ParseInt(id, 10, 64) folderID, err := strconv.ParseInt(id, 10, 64)
if err == nil { if err == nil {
folderIds = append(folderIds, folderId) folderIDs = append(folderIDs, folderID)
} }
} }
...@@ -48,9 +48,9 @@ func Search(c *m.ReqContext) { ...@@ -48,9 +48,9 @@ func Search(c *m.ReqContext) {
Limit: limit, Limit: limit,
IsStarred: starred == "true", IsStarred: starred == "true",
OrgId: c.OrgId, OrgId: c.OrgId,
DashboardIds: dbids, DashboardIds: dbIDs,
Type: dashboardType, Type: dashboardType,
FolderIds: folderIds, FolderIds: folderIDs,
Permission: permission, Permission: permission,
} }
......
...@@ -38,7 +38,7 @@ func UpdateTeam(c *m.ReqContext, cmd m.UpdateTeamCommand) Response { ...@@ -38,7 +38,7 @@ func UpdateTeam(c *m.ReqContext, cmd m.UpdateTeamCommand) Response {
} }
// DELETE /api/teams/:teamId // DELETE /api/teams/:teamId
func DeleteTeamById(c *m.ReqContext) Response { func DeleteTeamByID(c *m.ReqContext) Response {
if err := bus.Dispatch(&m.DeleteTeamCommand{OrgId: c.OrgId, Id: c.ParamsInt64(":teamId")}); err != nil { if err := bus.Dispatch(&m.DeleteTeamCommand{OrgId: c.OrgId, Id: c.ParamsInt64(":teamId")}); err != nil {
if err == m.ErrTeamNotFound { if err == m.ErrTeamNotFound {
return ApiError(404, "Failed to delete Team. ID not found", nil) return ApiError(404, "Failed to delete Team. ID not found", nil)
...@@ -82,7 +82,7 @@ func SearchTeams(c *m.ReqContext) Response { ...@@ -82,7 +82,7 @@ func SearchTeams(c *m.ReqContext) Response {
} }
// GET /api/teams/:teamId // GET /api/teams/:teamId
func GetTeamById(c *m.ReqContext) Response { func GetTeamByID(c *m.ReqContext) Response {
query := m.GetTeamByIdQuery{OrgId: c.OrgId, Id: c.ParamsInt64(":teamId")} query := m.GetTeamByIdQuery{OrgId: c.OrgId, Id: c.ParamsInt64(":teamId")}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
......
...@@ -14,12 +14,12 @@ func GetSignedInUser(c *m.ReqContext) Response { ...@@ -14,12 +14,12 @@ func GetSignedInUser(c *m.ReqContext) Response {
} }
// GET /api/users/:id // GET /api/users/:id
func GetUserById(c *m.ReqContext) Response { func GetUserByID(c *m.ReqContext) Response {
return getUserUserProfile(c.ParamsInt64(":id")) return getUserUserProfile(c.ParamsInt64(":id"))
} }
func getUserUserProfile(userId int64) Response { func getUserUserProfile(userID int64) Response {
query := m.GetUserProfileQuery{UserId: userId} query := m.GetUserProfileQuery{UserId: userID}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
if err == m.ErrUserNotFound { if err == m.ErrUserNotFound {
...@@ -75,14 +75,14 @@ func UpdateUser(c *m.ReqContext, cmd m.UpdateUserCommand) Response { ...@@ -75,14 +75,14 @@ func UpdateUser(c *m.ReqContext, cmd m.UpdateUserCommand) Response {
//POST /api/users/:id/using/:orgId //POST /api/users/:id/using/:orgId
func UpdateUserActiveOrg(c *m.ReqContext) Response { func UpdateUserActiveOrg(c *m.ReqContext) Response {
userId := c.ParamsInt64(":id") userID := c.ParamsInt64(":id")
orgId := c.ParamsInt64(":orgId") orgID := c.ParamsInt64(":orgId")
if !validateUsingOrg(userId, orgId) { if !validateUsingOrg(userID, orgID) {
return ApiError(401, "Not a valid organization", nil) return ApiError(401, "Not a valid organization", nil)
} }
cmd := m.SetUsingOrgCommand{UserId: userId, OrgId: orgId} cmd := m.SetUsingOrgCommand{UserId: userID, OrgId: orgID}
if err := bus.Dispatch(&cmd); err != nil { if err := bus.Dispatch(&cmd); err != nil {
return ApiError(500, "Failed to change active organization", err) return ApiError(500, "Failed to change active organization", err)
...@@ -116,8 +116,8 @@ func GetUserOrgList(c *m.ReqContext) Response { ...@@ -116,8 +116,8 @@ func GetUserOrgList(c *m.ReqContext) Response {
return getUserOrgList(c.ParamsInt64(":id")) return getUserOrgList(c.ParamsInt64(":id"))
} }
func getUserOrgList(userId int64) Response { func getUserOrgList(userID int64) Response {
query := m.GetUserOrgListQuery{UserId: userId} query := m.GetUserOrgListQuery{UserId: userID}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
return ApiError(500, "Failed to get user organizations", err) return ApiError(500, "Failed to get user organizations", err)
...@@ -126,8 +126,8 @@ func getUserOrgList(userId int64) Response { ...@@ -126,8 +126,8 @@ func getUserOrgList(userId int64) Response {
return Json(200, query.Result) return Json(200, query.Result)
} }
func validateUsingOrg(userId int64, orgId int64) bool { func validateUsingOrg(userID int64, orgID int64) bool {
query := m.GetUserOrgListQuery{UserId: userId} query := m.GetUserOrgListQuery{UserId: userID}
if err := bus.Dispatch(&query); err != nil { if err := bus.Dispatch(&query); err != nil {
return false return false
...@@ -136,7 +136,7 @@ func validateUsingOrg(userId int64, orgId int64) bool { ...@@ -136,7 +136,7 @@ func validateUsingOrg(userId int64, orgId int64) bool {
// validate that the org id in the list // validate that the org id in the list
valid := false valid := false
for _, other := range query.Result { for _, other := range query.Result {
if other.OrgId == orgId { if other.OrgId == orgID {
valid = true valid = true
} }
} }
...@@ -146,13 +146,13 @@ func validateUsingOrg(userId int64, orgId int64) bool { ...@@ -146,13 +146,13 @@ func validateUsingOrg(userId int64, orgId int64) bool {
// POST /api/user/using/:id // POST /api/user/using/:id
func UserSetUsingOrg(c *m.ReqContext) Response { func UserSetUsingOrg(c *m.ReqContext) Response {
orgId := c.ParamsInt64(":id") orgID := c.ParamsInt64(":id")
if !validateUsingOrg(c.UserId, orgId) { if !validateUsingOrg(c.UserId, orgID) {
return ApiError(401, "Not a valid organization", nil) return ApiError(401, "Not a valid organization", nil)
} }
cmd := m.SetUsingOrgCommand{UserId: c.UserId, OrgId: orgId} cmd := m.SetUsingOrgCommand{UserId: c.UserId, OrgId: orgID}
if err := bus.Dispatch(&cmd); err != nil { if err := bus.Dispatch(&cmd); err != nil {
return ApiError(500, "Failed to change active organization", err) return ApiError(500, "Failed to change active organization", err)
...@@ -163,13 +163,13 @@ func UserSetUsingOrg(c *m.ReqContext) Response { ...@@ -163,13 +163,13 @@ func UserSetUsingOrg(c *m.ReqContext) Response {
// GET /profile/switch-org/:id // GET /profile/switch-org/:id
func ChangeActiveOrgAndRedirectToHome(c *m.ReqContext) { func ChangeActiveOrgAndRedirectToHome(c *m.ReqContext) {
orgId := c.ParamsInt64(":id") orgID := c.ParamsInt64(":id")
if !validateUsingOrg(c.UserId, orgId) { if !validateUsingOrg(c.UserId, orgID) {
NotFoundHandler(c) NotFoundHandler(c)
} }
cmd := m.SetUsingOrgCommand{UserId: c.UserId, OrgId: orgId} cmd := m.SetUsingOrgCommand{UserId: c.UserId, OrgId: orgID}
if err := bus.Dispatch(&cmd); err != nil { if err := bus.Dispatch(&cmd); err != nil {
NotFoundHandler(c) NotFoundHandler(c)
......
...@@ -120,7 +120,7 @@ func (g *GrafanaServerImpl) initLogging() { ...@@ -120,7 +120,7 @@ func (g *GrafanaServerImpl) initLogging() {
} }
func (g *GrafanaServerImpl) startHttpServer() error { func (g *GrafanaServerImpl) startHttpServer() error {
g.httpServer = api.NewHttpServer() g.httpServer = api.NewHTTPServer()
err := g.httpServer.Start(g.context) err := g.httpServer.Start(g.context)
......
...@@ -17,10 +17,10 @@ type AuthOptions struct { ...@@ -17,10 +17,10 @@ type AuthOptions struct {
} }
func getRequestUserId(c *m.ReqContext) int64 { func getRequestUserId(c *m.ReqContext) int64 {
userId := c.Session.Get(session.SESS_KEY_USERID) userID := c.Session.Get(session.SESS_KEY_USERID)
if userId != nil { if userID != nil {
return userId.(int64) return userID.(int64)
} }
return 0 return 0
......
...@@ -20,7 +20,7 @@ func getDashboardUrlBySlug(orgId int64, slug string) (string, error) { ...@@ -20,7 +20,7 @@ func getDashboardUrlBySlug(orgId int64, slug string) (string, error) {
return m.GetDashboardUrl(query.Result.Uid, query.Result.Slug), nil return m.GetDashboardUrl(query.Result.Uid, query.Result.Slug), nil
} }
func RedirectFromLegacyDashboardUrl() macaron.Handler { func RedirectFromLegacyDashboardURL() macaron.Handler {
return func(c *m.ReqContext) { return func(c *m.ReqContext) {
slug := c.Params("slug") slug := c.Params("slug")
......
...@@ -13,7 +13,7 @@ import ( ...@@ -13,7 +13,7 @@ import (
func TestMiddlewareDashboardRedirect(t *testing.T) { func TestMiddlewareDashboardRedirect(t *testing.T) {
Convey("Given the dashboard redirect middleware", t, func() { Convey("Given the dashboard redirect middleware", t, func() {
bus.ClearBusHandlers() bus.ClearBusHandlers()
redirectFromLegacyDashboardUrl := RedirectFromLegacyDashboardUrl() redirectFromLegacyDashboardUrl := RedirectFromLegacyDashboardURL()
redirectFromLegacyDashboardSoloUrl := RedirectFromLegacyDashboardSoloUrl() redirectFromLegacyDashboardSoloUrl := RedirectFromLegacyDashboardSoloUrl()
fakeDash := m.NewDashboard("Child dash") fakeDash := m.NewDashboard("Child dash")
...@@ -34,9 +34,9 @@ func TestMiddlewareDashboardRedirect(t *testing.T) { ...@@ -34,9 +34,9 @@ func TestMiddlewareDashboardRedirect(t *testing.T) {
Convey("Should redirect to new dashboard url with a 301 Moved Permanently", func() { Convey("Should redirect to new dashboard url with a 301 Moved Permanently", func() {
So(sc.resp.Code, ShouldEqual, 301) So(sc.resp.Code, ShouldEqual, 301)
redirectUrl, _ := sc.resp.Result().Location() redirectURL, _ := sc.resp.Result().Location()
So(redirectUrl.Path, ShouldEqual, m.GetDashboardUrl(fakeDash.Uid, fakeDash.Slug)) So(redirectURL.Path, ShouldEqual, m.GetDashboardUrl(fakeDash.Uid, fakeDash.Slug))
So(len(redirectUrl.Query()), ShouldEqual, 2) So(len(redirectURL.Query()), ShouldEqual, 2)
}) })
}) })
...@@ -47,11 +47,11 @@ func TestMiddlewareDashboardRedirect(t *testing.T) { ...@@ -47,11 +47,11 @@ func TestMiddlewareDashboardRedirect(t *testing.T) {
Convey("Should redirect to new dashboard url with a 301 Moved Permanently", func() { Convey("Should redirect to new dashboard url with a 301 Moved Permanently", func() {
So(sc.resp.Code, ShouldEqual, 301) So(sc.resp.Code, ShouldEqual, 301)
redirectUrl, _ := sc.resp.Result().Location() redirectURL, _ := sc.resp.Result().Location()
expectedUrl := m.GetDashboardUrl(fakeDash.Uid, fakeDash.Slug) expectedURL := m.GetDashboardUrl(fakeDash.Uid, fakeDash.Slug)
expectedUrl = strings.Replace(expectedUrl, "/d/", "/d-solo/", 1) expectedURL = strings.Replace(expectedURL, "/d/", "/d-solo/", 1)
So(redirectUrl.Path, ShouldEqual, expectedUrl) So(redirectURL.Path, ShouldEqual, expectedURL)
So(len(redirectUrl.Query()), ShouldEqual, 2) So(len(redirectURL.Query()), ShouldEqual, 2)
}) })
}) })
}) })
......
...@@ -14,10 +14,10 @@ import ( ...@@ -14,10 +14,10 @@ import (
func TestRecoveryMiddleware(t *testing.T) { func TestRecoveryMiddleware(t *testing.T) {
Convey("Given an api route that panics", t, func() { Convey("Given an api route that panics", t, func() {
apiUrl := "/api/whatever" apiURL := "/api/whatever"
recoveryScenario("recovery middleware should return json", apiUrl, func(sc *scenarioContext) { recoveryScenario("recovery middleware should return json", apiURL, func(sc *scenarioContext) {
sc.handlerFunc = PanicHandler sc.handlerFunc = PanicHandler
sc.fakeReq("GET", apiUrl).exec() sc.fakeReq("GET", apiURL).exec()
sc.req.Header.Add("content-type", "application/json") sc.req.Header.Add("content-type", "application/json")
So(sc.resp.Code, ShouldEqual, 500) So(sc.resp.Code, ShouldEqual, 500)
...@@ -27,10 +27,10 @@ func TestRecoveryMiddleware(t *testing.T) { ...@@ -27,10 +27,10 @@ func TestRecoveryMiddleware(t *testing.T) {
}) })
Convey("Given a non-api route that panics", t, func() { Convey("Given a non-api route that panics", t, func() {
apiUrl := "/whatever" apiURL := "/whatever"
recoveryScenario("recovery middleware should return html", apiUrl, func(sc *scenarioContext) { recoveryScenario("recovery middleware should return html", apiURL, func(sc *scenarioContext) {
sc.handlerFunc = PanicHandler sc.handlerFunc = PanicHandler
sc.fakeReq("GET", apiUrl).exec() sc.fakeReq("GET", apiURL).exec()
So(sc.resp.Code, ShouldEqual, 500) So(sc.resp.Code, ShouldEqual, 500)
So(sc.resp.Header().Get("content-type"), ShouldEqual, "text/html; charset=UTF-8") So(sc.resp.Header().Get("content-type"), ShouldEqual, "text/html; charset=UTF-8")
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment