From 7aab6a88873f5516636b1d710736d47cc33e84d8 Mon Sep 17 00:00:00 2001 From: Julian Kornberger Date: Thu, 22 Mar 2018 12:37:35 +0100 Subject: [PATCH] Make golint happier --- pkg/api/admin_users.go | 14 ++-- pkg/api/alerting.go | 6 +- pkg/api/annotations.go | 34 ++++----- pkg/api/api.go | 38 +++++----- pkg/api/apikey.go | 6 +- pkg/api/app_routes.go | 4 +- pkg/api/dashboard.go | 39 +++++----- pkg/api/dashboard_permission.go | 16 ++-- pkg/api/dashboard_snapshot.go | 4 +- pkg/api/dashboard_test.go | 20 ++--- pkg/api/dataproxy.go | 8 +- pkg/api/datasources.go | 25 +++---- pkg/api/folder.go | 4 +- pkg/api/folder_test.go | 4 +- pkg/api/http_server.go | 2 +- pkg/api/index.go | 29 ++++---- pkg/api/login.go | 6 +- pkg/api/metrics.go | 6 +- pkg/api/org.go | 12 +-- pkg/api/org_invite.go | 31 ++++---- pkg/api/org_users.go | 18 ++--- pkg/api/playlist.go | 4 +- pkg/api/playlist_play.go | 56 +++++++------- pkg/api/plugins.go | 90 ++++++++++++----------- pkg/api/preferences.go | 10 +-- pkg/api/search.go | 16 ++-- pkg/api/team.go | 4 +- pkg/api/user.go | 36 ++++----- pkg/cmd/grafana-server/server.go | 2 +- pkg/middleware/auth.go | 6 +- pkg/middleware/dashboard_redirect.go | 2 +- pkg/middleware/dashboard_redirect_test.go | 18 ++--- pkg/middleware/recovery_test.go | 12 +-- 33 files changed, 289 insertions(+), 293 deletions(-) diff --git a/pkg/api/admin_users.go b/pkg/api/admin_users.go index 4cf7f4db4ec..dc3d390dda9 100644 --- a/pkg/api/admin_users.go +++ b/pkg/api/admin_users.go @@ -47,14 +47,14 @@ func AdminCreateUser(c *m.ReqContext, form dtos.AdminCreateUserForm) { } func AdminUpdateUserPassword(c *m.ReqContext, form dtos.AdminUpdateUserPasswordForm) { - userId := c.ParamsInt64(":id") + userID := c.ParamsInt64(":id") if len(form.Password) < 4 { c.JsonApiErr(400, "New password too short", nil) return } - userQuery := m.GetUserByIdQuery{Id: userId} + userQuery := m.GetUserByIdQuery{Id: userID} if err := bus.Dispatch(&userQuery); err != nil { c.JsonApiErr(500, "Could not read user from database", err) @@ -64,7 +64,7 @@ func AdminUpdateUserPassword(c *m.ReqContext, form dtos.AdminUpdateUserPasswordF passwordHashed := util.EncodePassword(form.Password, userQuery.Result.Salt) cmd := m.ChangeUserPasswordCommand{ - UserId: userId, + UserId: userID, NewPassword: passwordHashed, } @@ -77,10 +77,10 @@ func AdminUpdateUserPassword(c *m.ReqContext, form dtos.AdminUpdateUserPasswordF } func AdminUpdateUserPermissions(c *m.ReqContext, form dtos.AdminUpdateUserPermissionsForm) { - userId := c.ParamsInt64(":id") + userID := c.ParamsInt64(":id") cmd := m.UpdateUserPermissionsCommand{ - UserId: userId, + UserId: userID, IsGrafanaAdmin: form.IsGrafanaAdmin, } @@ -93,9 +93,9 @@ func AdminUpdateUserPermissions(c *m.ReqContext, form dtos.AdminUpdateUserPermis } 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 { c.JsonApiErr(500, "Failed to delete user", err) diff --git a/pkg/api/alerting.go b/pkg/api/alerting.go index eea4ef90c05..803823f6a94 100644 --- a/pkg/api/alerting.go +++ b/pkg/api/alerting.go @@ -26,9 +26,9 @@ func ValidateOrgAlert(c *m.ReqContext) { } 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) } @@ -151,7 +151,7 @@ func GetAlertNotifications(c *m.ReqContext) Response { return Json(200, result) } -func GetAlertNotificationById(c *m.ReqContext) Response { +func GetAlertNotificationByID(c *m.ReqContext) Response { query := &m.GetAlertNotificationsQuery{ OrgId: c.OrgId, Id: c.ParamsInt64("notificationId"), diff --git a/pkg/api/annotations.go b/pkg/api/annotations.go index fb75e0bf129..b4e328793cc 100644 --- a/pkg/api/annotations.go +++ b/pkg/api/annotations.go @@ -52,7 +52,7 @@ func (e *CreateAnnotationError) Error() string { } 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) } @@ -179,18 +179,18 @@ func PostGraphiteAnnotation(c *m.ReqContext, cmd dtos.PostGraphiteAnnotationsCmd } func UpdateAnnotation(c *m.ReqContext, cmd dtos.UpdateAnnotationsCmd) Response { - annotationId := c.ParamsInt64(":annotationId") + annotationID := c.ParamsInt64(":annotationId") repo := annotations.GetRepository() - if resp := canSave(c, repo, annotationId); resp != nil { + if resp := canSave(c, repo, annotationID); resp != nil { return resp } item := annotations.Item{ OrgId: c.OrgId, UserId: c.UserId, - Id: annotationId, + Id: annotationID, Epoch: cmd.Time / 1000, Text: cmd.Text, Tags: cmd.Tags, @@ -254,14 +254,14 @@ func DeleteAnnotationById(c *m.ReqContext) Response { func DeleteAnnotationRegion(c *m.ReqContext) Response { 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 } err := repo.Delete(&annotations.DeleteParams{ - RegionId: regionId, + RegionId: regionID, }) if err != nil { @@ -271,13 +271,13 @@ func DeleteAnnotationRegion(c *m.ReqContext) Response { return ApiSuccess("Annotation region deleted") } -func canSaveByDashboardId(c *m.ReqContext, dashboardId int64) (bool, error) { - if dashboardId == 0 && !c.SignedInUser.HasRole(m.ROLE_EDITOR) { +func canSaveByDashboardID(c *m.ReqContext, dashboardID int64) (bool, error) { + if dashboardID == 0 && !c.SignedInUser.HasRole(m.ROLE_EDITOR) { return false, nil } - if dashboardId > 0 { - guardian := guardian.New(dashboardId, c.OrgId, c.SignedInUser) + if dashboardID > 0 { + guardian := guardian.New(dashboardID, c.OrgId, c.SignedInUser) if canEdit, err := guardian.CanEdit(); err != nil || !canEdit { return false, err } @@ -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) } - 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 nil } -func canSaveByRegionId(c *m.ReqContext, repo annotations.Repository, regionId int64) Response { - items, err := repo.Find(&annotations.ItemQuery{RegionId: regionId, OrgId: c.OrgId}) +func canSaveByRegionID(c *m.ReqContext, repo annotations.Repository, regionID int64) Response { + items, err := repo.Find(&annotations.ItemQuery{RegionId: regionID, OrgId: c.OrgId}) if err != nil || len(items) == 0 { 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) } diff --git a/pkg/api/api.go b/pkg/api/api.go index 5b3cde09fd5..22d5d773d2a 100644 --- a/pkg/api/api.go +++ b/pkg/api/api.go @@ -15,7 +15,7 @@ func (hs *HttpServer) registerRoutes() { reqGrafanaAdmin := middleware.Auth(&middleware.AuthOptions{ReqSignedIn: true, ReqGrafanaAdmin: true}) reqEditorRole := middleware.RoleAuth(m.ROLE_EDITOR, m.ROLE_ADMIN) reqOrgAdmin := middleware.RoleAuth(m.ROLE_ADMIN) - redirectFromLegacyDashboardUrl := middleware.RedirectFromLegacyDashboardUrl() + redirectFromLegacyDashboardUrl := middleware.RedirectFromLegacyDashboardURL() redirectFromLegacyDashboardSoloUrl := middleware.RedirectFromLegacyDashboardSoloUrl() quota := middleware.Quota bind := binding.Bind @@ -110,7 +110,7 @@ func (hs *HttpServer) registerRoutes() { r.Get("/api/snapshots-delete/:key", reqEditorRole, wrap(DeleteDashboardSnapshot)) // 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 r.Group("/api", func(apiRoute RouteRegister) { @@ -139,7 +139,7 @@ func (hs *HttpServer) registerRoutes() { apiRoute.Group("/users", func(usersRoute RouteRegister) { usersRoute.Get("/", wrap(SearchUsers)) usersRoute.Get("/search", wrap(SearchUsersWithPaging)) - usersRoute.Get("/:id", wrap(GetUserById)) + usersRoute.Get("/:id", wrap(GetUserByID)) usersRoute.Get("/:id/orgs", wrap(GetUserOrgList)) // query parameters /users/lookup?loginOrEmail=admin@example.com usersRoute.Get("/lookup", wrap(GetUserByLoginOrEmail)) @@ -149,11 +149,11 @@ func (hs *HttpServer) registerRoutes() { // team (admin permission required) apiRoute.Group("/teams", func(teamsRoute RouteRegister) { - teamsRoute.Get("/:teamId", wrap(GetTeamById)) + teamsRoute.Get("/:teamId", wrap(GetTeamByID)) teamsRoute.Get("/search", wrap(SearchTeams)) teamsRoute.Post("/", bind(m.CreateTeamCommand{}), wrap(CreateTeam)) 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.Post("/:teamId/members", bind(m.AddTeamMemberCommand{}), wrap(AddTeamMember)) teamsRoute.Delete("/:teamId/members/:userId", wrap(RemoveTeamMember)) @@ -192,10 +192,10 @@ func (hs *HttpServer) registerRoutes() { // orgs (admin routes) apiRoute.Group("/orgs/:orgId", func(orgsRoute RouteRegister) { - orgsRoute.Get("/", wrap(GetOrgById)) + orgsRoute.Get("/", wrap(GetOrgByID)) orgsRoute.Put("/", bind(dtos.UpdateOrgForm{}), wrap(UpdateOrg)) orgsRoute.Put("/address", bind(dtos.UpdateOrgAddressForm{}), wrap(UpdateOrgAddress)) - orgsRoute.Delete("/", wrap(DeleteOrgById)) + orgsRoute.Delete("/", wrap(DeleteOrgByID)) orgsRoute.Get("/users", wrap(GetOrgUsers)) orgsRoute.Post("/users", bind(m.AddOrgUserCommand{}), wrap(AddOrgUser)) orgsRoute.Patch("/users/:userId", bind(m.UpdateOrgUserCommand{}), wrap(UpdateOrgUser)) @@ -211,9 +211,9 @@ func (hs *HttpServer) registerRoutes() { // auth api keys apiRoute.Group("/auth/keys", func(keysRoute RouteRegister) { - keysRoute.Get("/", wrap(GetApiKeys)) - keysRoute.Post("/", quota("api_key"), bind(m.AddApiKeyCommand{}), wrap(AddApiKey)) - keysRoute.Delete("/:id", wrap(DeleteApiKey)) + keysRoute.Get("/", wrap(GetAPIKeys)) + keysRoute.Post("/", quota("api_key"), bind(m.AddApiKeyCommand{}), wrap(AddAPIKey)) + keysRoute.Delete("/:id", wrap(DeleteAPIKey)) }, reqOrgAdmin) // Preferences @@ -226,16 +226,16 @@ func (hs *HttpServer) registerRoutes() { datasourceRoute.Get("/", wrap(GetDataSources)) datasourceRoute.Post("/", quota("data_source"), bind(m.AddDataSourceCommand{}), wrap(AddDataSource)) 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.Get("/:id", wrap(GetDataSourceById)) + datasourceRoute.Get("/:id", wrap(GetDataSourceByID)) datasourceRoute.Get("/name/:name", wrap(GetDataSourceByName)) }, 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/:pluginId/settings", wrap(GetPluginSettingById)) + apiRoute.Get("/plugins/:pluginId/settings", wrap(GetPluginSettingByID)) apiRoute.Get("/plugins/:pluginId/markdown/:name", wrap(GetPluginMarkdown)) apiRoute.Group("/plugins", func(pluginRoute RouteRegister) { @@ -250,11 +250,11 @@ func (hs *HttpServer) registerRoutes() { // Folders apiRoute.Group("/folders", func(folderRoute RouteRegister) { folderRoute.Get("/", wrap(GetFolders)) - folderRoute.Get("/id/:id", wrap(GetFolderById)) + folderRoute.Get("/id/:id", wrap(GetFolderByID)) folderRoute.Post("/", bind(m.CreateFolderCommand{}), wrap(CreateFolder)) folderRoute.Group("/:uid", func(folderUidRoute RouteRegister) { - folderUidRoute.Get("/", wrap(GetFolderByUid)) + folderUidRoute.Get("/", wrap(GetFolderByUID)) folderUidRoute.Put("/", bind(m.UpdateFolderCommand{}), wrap(UpdateFolder)) folderUidRoute.Delete("/", wrap(DeleteFolder)) @@ -268,7 +268,7 @@ func (hs *HttpServer) registerRoutes() { // Dashboard apiRoute.Group("/dashboards", func(dashboardRoute RouteRegister) { 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.Delete("/db/:slug", wrap(DeleteDashboard)) @@ -314,7 +314,7 @@ func (hs *HttpServer) registerRoutes() { // metrics apiRoute.Post("/tsdb/query", bind(dtos.MetricRequest{}), wrap(QueryMetrics)) 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.Group("/alerts", func(alertsRoute RouteRegister) { @@ -332,7 +332,7 @@ func (hs *HttpServer) registerRoutes() { alertNotifications.Post("/test", bind(dtos.NotificationTestCommand{}), wrap(NotificationTest)) alertNotifications.Post("/", bind(m.CreateAlertNotificationCommand{}), wrap(CreateAlertNotification)) alertNotifications.Put("/:notificationId", bind(m.UpdateAlertNotificationCommand{}), wrap(UpdateAlertNotification)) - alertNotifications.Get("/:notificationId", wrap(GetAlertNotificationById)) + alertNotifications.Get("/:notificationId", wrap(GetAlertNotificationByID)) alertNotifications.Delete("/:notificationId", wrap(DeleteAlertNotification)) }, reqEditorRole) diff --git a/pkg/api/apikey.go b/pkg/api/apikey.go index 24ed69ec691..7195c7453f6 100644 --- a/pkg/api/apikey.go +++ b/pkg/api/apikey.go @@ -7,7 +7,7 @@ import ( 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} if err := bus.Dispatch(&query); err != nil { @@ -26,7 +26,7 @@ func GetApiKeys(c *m.ReqContext) Response { return Json(200, result) } -func DeleteApiKey(c *m.ReqContext) Response { +func DeleteAPIKey(c *m.ReqContext) Response { id := c.ParamsInt64(":id") cmd := &m.DeleteApiKeyCommand{Id: id, OrgId: c.OrgId} @@ -39,7 +39,7 @@ func DeleteApiKey(c *m.ReqContext) Response { 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() { return ApiError(400, "Invalid role specified", nil) } diff --git a/pkg/api/app_routes.go b/pkg/api/app_routes.go index 8d74d96396b..0b7dcd32ce3 100644 --- a/pkg/api/app_routes.go +++ b/pkg/api/app_routes.go @@ -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) { path := c.Params("*") - proxy := pluginproxy.NewApiPluginProxy(c, path, route, appId) + proxy := pluginproxy.NewApiPluginProxy(c, path, route, appID) proxy.Transport = pluginProxyTransport proxy.ServeHTTP(c.Resp, c.Req.Request) } diff --git a/pkg/api/dashboard.go b/pkg/api/dashboard.go index 877524ad5dd..25c89238933 100644 --- a/pkg/api/dashboard.go +++ b/pkg/api/dashboard.go @@ -22,12 +22,12 @@ import ( "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 { 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 { return false, err } @@ -114,24 +114,22 @@ func GetDashboard(c *m.ReqContext) Response { return Json(200, dto) } -func getUserLogin(userId int64) string { - query := m.GetUserByIdQuery{Id: userId} +func getUserLogin(userID int64) string { + query := m.GetUserByIdQuery{Id: userID} err := bus.Dispatch(&query) if err != nil { 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 if len(uid) > 0 { - query = m.GetDashboardQuery{Uid: uid, Id: id, OrgId: orgId} + query = m.GetDashboardQuery{Uid: uid, Id: id, OrgId: orgID} } 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 { @@ -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")) if rsp != nil { return rsp @@ -291,9 +289,8 @@ func GetHomeDashboard(c *m.ReqContext) Response { url := m.GetDashboardUrl(slugQuery.Result.Uid, slugQuery.Result.Slug) dashRedirect := dtos.DashboardRedirect{RedirectUri: url} 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") @@ -339,22 +336,22 @@ func addGettingStartedPanelToHomeDashboard(dash *simplejson.Json) { // GetDashboardVersions returns all dashboard versions as JSON 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 { return dashboardGuardianResponse(err) } query := m.GetDashboardVersionsQuery{ OrgId: c.OrgId, - DashboardId: dashId, + DashboardId: dashID, Limit: c.QueryInt("limit"), Start: c.QueryInt("start"), } 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 { @@ -378,21 +375,21 @@ func GetDashboardVersions(c *m.ReqContext) Response { // GetDashboardVersion returns the dashboard version with the given ID. 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 { return dashboardGuardianResponse(err) } query := m.GetDashboardVersionQuery{ OrgId: c.OrgId, - DashboardId: dashId, + DashboardId: dashID, Version: c.ParamsInt(":id"), } 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" diff --git a/pkg/api/dashboard_permission.go b/pkg/api/dashboard_permission.go index a62c27ab320..c852033829a 100644 --- a/pkg/api/dashboard_permission.go +++ b/pkg/api/dashboard_permission.go @@ -10,14 +10,14 @@ import ( ) 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 { 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 { return dashboardGuardianResponse(err) @@ -38,25 +38,25 @@ func GetDashboardPermissionList(c *m.ReqContext) 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 { 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 { return dashboardGuardianResponse(err) } cmd := m.UpdateDashboardAclCommand{} - cmd.DashboardId = dashId + cmd.DashboardId = dashID for _, item := range apiCmd.Items { cmd.Items = append(cmd.Items, &m.DashboardAcl{ OrgId: c.OrgId, - DashboardId: dashId, + DashboardId: dashID, UserId: item.UserId, TeamId: item.TeamId, Role: item.Role, diff --git a/pkg/api/dashboard_snapshot.go b/pkg/api/dashboard_snapshot.go index 4656940d2bb..b74dfe5fd34 100644 --- a/pkg/api/dashboard_snapshot.go +++ b/pkg/api/dashboard_snapshot.go @@ -106,9 +106,9 @@ func DeleteDashboardSnapshot(c *m.ReqContext) Response { return ApiError(404, "Failed to get dashboard snapshot", nil) } 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() if err != nil { return ApiError(500, "Error while checking permissions for snapshot", err) diff --git a/pkg/api/dashboard_test.go b/pkg/api/dashboard_test.go index 6c5b4e4c102..d940c5406be 100644 --- a/pkg/api/dashboard_test.go +++ b/pkg/api/dashboard_test.go @@ -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) { - CallDeleteDashboardByUid(sc) + CallDeleteDashboardByUID(sc) So(sc.resp.Code, ShouldEqual, 403) Convey("Should lookup dashboard by uid", func() { @@ -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) { - CallDeleteDashboardByUid(sc) + CallDeleteDashboardByUID(sc) So(sc.resp.Code, ShouldEqual, 200) Convey("Should lookup dashboard by uid", func() { @@ -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) { - CallDeleteDashboardByUid(sc) + CallDeleteDashboardByUID(sc) So(sc.resp.Code, ShouldEqual, 403) Convey("Should lookup dashboard by uid", func() { @@ -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) { - CallDeleteDashboardByUid(sc) + CallDeleteDashboardByUID(sc) So(sc.resp.Code, ShouldEqual, 403) Convey("Should lookup dashboard by uid", func() { @@ -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) { - CallDeleteDashboardByUid(sc) + CallDeleteDashboardByUID(sc) So(sc.resp.Code, ShouldEqual, 200) Convey("Should lookup dashboard by uid", func() { @@ -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) { - CallDeleteDashboardByUid(sc) + CallDeleteDashboardByUID(sc) So(sc.resp.Code, ShouldEqual, 403) Convey("Should lookup dashboard by uid", func() { @@ -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) { - CallDeleteDashboardByUid(sc) + CallDeleteDashboardByUID(sc) So(sc.resp.Code, ShouldEqual, 200) Convey("Should lookup dashboard by uid", func() { @@ -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) { - CallDeleteDashboardByUid(sc) + CallDeleteDashboardByUID(sc) So(sc.resp.Code, ShouldEqual, 403) Convey("Should lookup dashboard by uid", func() { @@ -837,12 +837,12 @@ func CallDeleteDashboard(sc *scenarioContext) { 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 { return nil }) - sc.handlerFunc = DeleteDashboardByUid + sc.handlerFunc = DeleteDashboardByUID sc.fakeReqWithParams("DELETE", sc.url, map[string]string{}).exec() } diff --git a/pkg/api/dataproxy.go b/pkg/api/dataproxy.go index c6fe8b6cd8c..2e97e5d2d6f 100644 --- a/pkg/api/dataproxy.go +++ b/pkg/api/dataproxy.go @@ -13,19 +13,19 @@ import ( 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) if !nocache { if cached, found := hs.cache.Get(cacheKey); found { ds := cached.(*m.DataSource) - if ds.OrgId == orgId { + if ds.OrgId == orgID { return ds, nil } } } - query := m.GetDataSourceByIdQuery{Id: id, OrgId: orgId} + query := m.GetDataSourceByIdQuery{Id: id, OrgId: orgID} if err := bus.Dispatch(&query); err != nil { return nil, err } @@ -39,7 +39,7 @@ func (hs *HttpServer) ProxyDataSourceRequest(c *m.ReqContext) { 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 { c.JsonApiErr(500, "Unable to load datasource meta data", err) diff --git a/pkg/api/datasources.go b/pkg/api/datasources.go index ed8fc5d2a66..4b5aa56d6e7 100644 --- a/pkg/api/datasources.go +++ b/pkg/api/datasources.go @@ -49,7 +49,7 @@ func GetDataSources(c *m.ReqContext) Response { return Json(200, &result) } -func GetDataSourceById(c *m.ReqContext) Response { +func GetDataSourceByID(c *m.ReqContext) Response { query := m.GetDataSourceByIdQuery{ Id: c.ParamsInt64(":id"), OrgId: c.OrgId, @@ -68,14 +68,14 @@ func GetDataSourceById(c *m.ReqContext) Response { return Json(200, &dtos) } -func DeleteDataSourceById(c *m.ReqContext) Response { +func DeleteDataSourceByID(c *m.ReqContext) Response { id := c.ParamsInt64(":id") if id <= 0 { return ApiError(400, "Missing valid datasource id", nil) } - ds, err := getRawDataSourceById(id, c.OrgId) + ds, err := getRawDataSourceByID(id, c.OrgId) if err != nil { return ApiError(400, "Failed to delete datasource", nil) } @@ -143,7 +143,7 @@ func UpdateDataSource(c *m.ReqContext, cmd m.UpdateDataSourceCommand) Response { cmd.OrgId = c.OrgId cmd.Id = c.ParamsInt64(":id") - err := fillWithSecureJsonData(&cmd) + err := fillWithSecureJSONData(&cmd) if err != nil { return ApiError(500, "Failed to update datasource", err) } @@ -152,9 +152,8 @@ func UpdateDataSource(c *m.ReqContext, cmd m.UpdateDataSourceCommand) Response { if err != nil { if err == m.ErrDataSourceUpdatingOldVersion { 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) return Json(200, util.DynMap{ @@ -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 { return nil } - ds, err := getRawDataSourceById(cmd.Id, cmd.OrgId) + ds, err := getRawDataSourceByID(cmd.Id, cmd.OrgId) if err != nil { return err } @@ -179,8 +178,8 @@ func fillWithSecureJsonData(cmd *m.UpdateDataSourceCommand) error { return m.ErrDatasourceIsReadOnly } - secureJsonData := ds.SecureJsonData.Decrypt() - for k, v := range secureJsonData { + secureJSONData := ds.SecureJsonData.Decrypt() + for k, v := range secureJSONData { if _, ok := cmd.SecureJsonData[k]; !ok { cmd.SecureJsonData[k] = v @@ -190,10 +189,10 @@ func fillWithSecureJsonData(cmd *m.UpdateDataSourceCommand) error { return nil } -func getRawDataSourceById(id int64, orgId int64) (*m.DataSource, error) { +func getRawDataSourceByID(id int64, orgID int64) (*m.DataSource, error) { query := m.GetDataSourceByIdQuery{ Id: id, - OrgId: orgId, + OrgId: orgID, } if err := bus.Dispatch(&query); err != nil { @@ -220,7 +219,7 @@ func GetDataSourceByName(c *m.ReqContext) Response { } // 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} if err := bus.Dispatch(&query); err != nil { diff --git a/pkg/api/folder.go b/pkg/api/folder.go index 143892fa6e8..e88f7fc2c3b 100644 --- a/pkg/api/folder.go +++ b/pkg/api/folder.go @@ -31,7 +31,7 @@ func GetFolders(c *m.ReqContext) Response { return Json(200, result) } -func GetFolderByUid(c *m.ReqContext) Response { +func GetFolderByUID(c *m.ReqContext) Response { s := dashboards.NewFolderService(c.OrgId, c.SignedInUser) folder, err := s.GetFolderByUid(c.Params(":uid")) @@ -43,7 +43,7 @@ func GetFolderByUid(c *m.ReqContext) Response { 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) folder, err := s.GetFolderById(c.ParamsInt64(":id")) if err != nil { diff --git a/pkg/api/folder_test.go b/pkg/api/folder_test.go index 7cefdcf8544..e3c63ac0745 100644 --- a/pkg/api/folder_test.go +++ b/pkg/api/folder_test.go @@ -133,8 +133,8 @@ func TestFoldersApiEndpoint(t *testing.T) { }) } -func callGetFolderByUid(sc *scenarioContext) { - sc.handlerFunc = GetFolderByUid +func callGetFolderByUID(sc *scenarioContext) { + sc.handlerFunc = GetFolderByUID sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec() } diff --git a/pkg/api/http_server.go b/pkg/api/http_server.go index c6a9286a5d8..772a27bd4cd 100644 --- a/pkg/api/http_server.go +++ b/pkg/api/http_server.go @@ -39,7 +39,7 @@ type HttpServer struct { httpSrv *http.Server } -func NewHttpServer() *HttpServer { +func NewHTTPServer() *HttpServer { return &HttpServer{ log: log.New("http.server"), cache: gocache.New(5*time.Minute, 10*time.Minute), diff --git a/pkg/api/index.go b/pkg/api/index.go index e50c59e082a..a1d21d1c686 100644 --- a/pkg/api/index.go +++ b/pkg/api/index.go @@ -32,13 +32,13 @@ func setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, error) { locale = parts[0] } - appUrl := setting.AppUrl - appSubUrl := setting.AppSubUrl + appURL := setting.AppUrl + appSubURL := setting.AppSubUrl // special case when doing localhost call from phantomjs if c.IsRenderCall { - appUrl = fmt.Sprintf("%s://localhost:%s", setting.Protocol, setting.HttpPort) - appSubUrl = "" + appURL = fmt.Sprintf("%s://localhost:%s", setting.Protocol, setting.HttpPort) + appSubURL = "" settings["appSubUrl"] = "" } @@ -62,8 +62,8 @@ func setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, error) { }, Settings: settings, Theme: prefs.Theme, - AppUrl: appUrl, - AppSubUrl: appSubUrl, + AppUrl: appURL, + AppSubUrl: appSubURL, GoogleAnalyticsId: setting.GoogleAnalyticsId, GoogleTagManagerId: setting.GoogleTagManagerId, BuildVersion: setting.BuildVersion, @@ -80,8 +80,8 @@ func setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, error) { data.User.Name = data.User.Login } - themeUrlParam := c.Query("theme") - if themeUrlParam == "light" { + themeURLParam := c.Query("theme") + if themeURLParam == "light" { data.User.LightTheme = true data.Theme = "light" } @@ -299,12 +299,12 @@ func setIndexViewData(c *m.ReqContext) (*dtos.IndexViewData, error) { } 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) return - } else { - c.HTML(200, "index", data) } + c.HTML(200, "index", data) } func NotFoundHandler(c *m.ReqContext) { @@ -313,10 +313,11 @@ func NotFoundHandler(c *m.ReqContext) { return } - if data, err := setIndexViewData(c); err != nil { + data, err := setIndexViewData(c) + if err != nil { c.Handle(500, "Failed to get settings", err) return - } else { - c.HTML(404, "index", data) } + + c.HTML(404, "index", data) } diff --git a/pkg/api/login.go b/pkg/api/login.go index 2ca2ce5a3e2..dc5ae730721 100644 --- a/pkg/api/login.go +++ b/pkg/api/login.go @@ -14,7 +14,7 @@ import ( ) const ( - VIEW_INDEX = "index" + ViewIndex = "index" ) func LoginView(c *m.ReqContext) { @@ -40,7 +40,7 @@ func LoginView(c *m.ReqContext) { } if !tryLoginUsingRememberCookie(c) { - c.HTML(200, VIEW_INDEX, viewData) + c.HTML(200, ViewIndex, viewData) return } @@ -87,7 +87,7 @@ func tryLoginUsingRememberCookie(c *m.ReqContext) bool { return true } -func LoginApiPing(c *m.ReqContext) { +func LoginAPIPing(c *m.ReqContext) { if !tryLoginUsingRememberCookie(c) { c.JsonApiErr(401, "Unauthorized", nil) return diff --git a/pkg/api/metrics.go b/pkg/api/metrics.go index 5d395d655a9..38bb8dc0688 100644 --- a/pkg/api/metrics.go +++ b/pkg/api/metrics.go @@ -20,12 +20,12 @@ func QueryMetrics(c *m.ReqContext, reqDto dtos.MetricRequest) Response { 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 { 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 { return ApiError(500, "failed to fetch data source", err) } @@ -82,7 +82,7 @@ func GenerateError(c *m.ReqContext) Response { } // 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 { return ApiError(500, "Failed to insert test data", err) } diff --git a/pkg/api/org.go b/pkg/api/org.go index 5f20559dbbe..7735bd6a7eb 100644 --- a/pkg/api/org.go +++ b/pkg/api/org.go @@ -15,7 +15,7 @@ func GetOrgCurrent(c *m.ReqContext) Response { } // GET /api/orgs/:orgId -func GetOrgById(c *m.ReqContext) Response { +func GetOrgByID(c *m.ReqContext) Response { return getOrgHelper(c.ParamsInt64(":orgId")) } @@ -106,8 +106,8 @@ func UpdateOrg(c *m.ReqContext, form dtos.UpdateOrgForm) Response { return updateOrgHelper(form, c.ParamsInt64(":orgId")) } -func updateOrgHelper(form dtos.UpdateOrgForm, orgId int64) Response { - cmd := m.UpdateOrgCommand{Name: form.Name, OrgId: orgId} +func updateOrgHelper(form dtos.UpdateOrgForm, orgID int64) Response { + cmd := m.UpdateOrgCommand{Name: form.Name, OrgId: orgID} if err := bus.Dispatch(&cmd); err != nil { if err == m.ErrOrgNameTaken { return ApiError(400, "Organization name taken", err) @@ -128,9 +128,9 @@ func UpdateOrgAddress(c *m.ReqContext, form dtos.UpdateOrgAddressForm) Response 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{ - OrgId: orgId, + OrgId: orgID, Address: m.Address{ Address1: form.Address1, Address2: form.Address2, @@ -149,7 +149,7 @@ func updateOrgAddressHelper(form dtos.UpdateOrgAddressForm, orgId int64) Respons } // 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 == m.ErrOrgNotFound { return ApiError(404, "Failed to delete organization. ID not found", nil) diff --git a/pkg/api/org_invite.go b/pkg/api/org_invite.go index 6a727dd95cc..0486287a31b 100644 --- a/pkg/api/org_invite.go +++ b/pkg/api/org_invite.go @@ -96,26 +96,25 @@ 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(500, "Error while trying to create org user", err) - } else { + } - if inviteDto.SendEmail && util.IsEmail(user.Email) { - emailCmd := m.SendEmailCommand{ - To: []string{user.Email}, - Template: "invited_to_org.html", - Data: map[string]interface{}{ - "Name": user.NameOrFallback(), - "OrgName": c.OrgName, - "InvitedBy": util.StringsFallback3(c.Name, c.Email, c.Login), - }, - } - - if err := bus.Dispatch(&emailCmd); err != nil { - return ApiError(500, "Failed to send email invited_to_org", err) - } + if inviteDto.SendEmail && util.IsEmail(user.Email) { + emailCmd := m.SendEmailCommand{ + To: []string{user.Email}, + Template: "invited_to_org.html", + Data: map[string]interface{}{ + "Name": user.NameOrFallback(), + "OrgName": c.OrgName, + "InvitedBy": util.StringsFallback3(c.Name, c.Email, c.Login), + }, } - return ApiSuccess(fmt.Sprintf("Existing Grafana user %s added to org %s", user.NameOrFallback(), c.OrgName)) + if err := bus.Dispatch(&emailCmd); err != nil { + return ApiError(500, "Failed to send email invited_to_org", err) + } } + + return ApiSuccess(fmt.Sprintf("Existing Grafana user %s added to org %s", user.NameOrFallback(), c.OrgName)) } func RevokeInvite(c *m.ReqContext) Response { diff --git a/pkg/api/org_users.go b/pkg/api/org_users.go index 6d7c2bb94bd..cd1430d22fb 100644 --- a/pkg/api/org_users.go +++ b/pkg/api/org_users.go @@ -53,9 +53,9 @@ func GetOrgUsers(c *m.ReqContext) Response { 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{ - OrgId: orgId, + OrgId: orgID, Query: query, Limit: limit, } @@ -102,19 +102,19 @@ func updateOrgUserHelper(cmd m.UpdateOrgUserCommand) Response { // DELETE /api/org/users/:userId func RemoveOrgUserForCurrentOrg(c *m.ReqContext) Response { - userId := c.ParamsInt64(":userId") - return removeOrgUserHelper(c.OrgId, userId) + userID := c.ParamsInt64(":userId") + return removeOrgUserHelper(c.OrgId, userID) } // DELETE /api/orgs/:orgId/users/:userId func RemoveOrgUser(c *m.ReqContext) Response { - userId := c.ParamsInt64(":userId") - orgId := c.ParamsInt64(":orgId") - return removeOrgUserHelper(orgId, userId) + userID := c.ParamsInt64(":userId") + orgID := c.ParamsInt64(":orgId") + return removeOrgUserHelper(orgID, userID) } -func removeOrgUserHelper(orgId int64, userId int64) Response { - cmd := m.RemoveOrgUserCommand{OrgId: orgId, UserId: userId} +func removeOrgUserHelper(orgID int64, userID int64) Response { + cmd := m.RemoveOrgUserCommand{OrgId: orgID, UserId: userID} if err := bus.Dispatch(&cmd); err != nil { if err == m.ErrLastOrgAdmin { diff --git a/pkg/api/playlist.go b/pkg/api/playlist.go index 45de40ce337..0198850252d 100644 --- a/pkg/api/playlist.go +++ b/pkg/api/playlist.go @@ -127,9 +127,9 @@ func GetPlaylistItems(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 { return ApiError(500, "Could not load dashboards", err) } diff --git a/pkg/api/playlist_play.go b/pkg/api/playlist_play.go index 1d059e06be5..69a2caef7e0 100644 --- a/pkg/api/playlist_play.go +++ b/pkg/api/playlist_play.go @@ -34,29 +34,27 @@ func populateDashboardsById(dashboardByIds []int64, dashboardIdOrder map[int64]i 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) - if len(dashboardByTag) > 0 { - for _, tag := range dashboardByTag { - searchQuery := search.Query{ - Title: "", - Tags: []string{tag}, - SignedInUser: signedInUser, - Limit: 100, - IsStarred: false, - OrgId: orgId, - } + for _, tag := range dashboardByTag { + searchQuery := search.Query{ + Title: "", + Tags: []string{tag}, + SignedInUser: signedInUser, + Limit: 100, + IsStarred: false, + OrgId: orgID, + } - if err := bus.Dispatch(&searchQuery); err == nil { - for _, item := range searchQuery.Result { - result = append(result, dtos.PlaylistDashboard{ - Id: item.Id, - Title: item.Title, - Uri: item.Uri, - Order: dashboardTagOrder[tag], - }) - } + if err := bus.Dispatch(&searchQuery); err == nil { + for _, item := range searchQuery.Result { + result = append(result, dtos.PlaylistDashboard{ + Id: item.Id, + Title: item.Title, + Uri: item.Uri, + Order: dashboardTagOrder[tag], + }) } } } @@ -64,19 +62,19 @@ func populateDashboardsByTag(orgId int64, signedInUser *m.SignedInUser, dashboar return result } -func LoadPlaylistDashboards(orgId int64, signedInUser *m.SignedInUser, playlistId int64) (dtos.PlaylistDashboardsSlice, error) { - playlistItems, _ := LoadPlaylistItems(playlistId) +func LoadPlaylistDashboards(orgID int64, signedInUser *m.SignedInUser, playlistID int64) (dtos.PlaylistDashboardsSlice, error) { + playlistItems, _ := LoadPlaylistItems(playlistID) - dashboardByIds := make([]int64, 0) + dashboardByIDs := make([]int64, 0) dashboardByTag := make([]string, 0) - dashboardIdOrder := make(map[int64]int) + dashboardIDOrder := make(map[int64]int) dashboardTagOrder := make(map[string]int) for _, i := range playlistItems { if i.Type == "dashboard_by_id" { - dashboardId, _ := strconv.ParseInt(i.Value, 10, 64) - dashboardByIds = append(dashboardByIds, dashboardId) - dashboardIdOrder[dashboardId] = i.Order + dashboardID, _ := strconv.ParseInt(i.Value, 10, 64) + dashboardByIDs = append(dashboardByIDs, dashboardID) + dashboardIDOrder[dashboardID] = i.Order } if i.Type == "dashboard_by_tag" { @@ -87,9 +85,9 @@ func LoadPlaylistDashboards(orgId int64, signedInUser *m.SignedInUser, playlistI result := make(dtos.PlaylistDashboardsSlice, 0) - var k, _ = populateDashboardsById(dashboardByIds, dashboardIdOrder) + var k, _ = populateDashboardsById(dashboardByIDs, dashboardIDOrder) result = append(result, k...) - result = append(result, populateDashboardsByTag(orgId, signedInUser, dashboardByTag, dashboardTagOrder)...) + result = append(result, populateDashboardsByTag(orgID, signedInUser, dashboardByTag, dashboardTagOrder)...) sort.Sort(result) return result, nil diff --git a/pkg/api/plugins.go b/pkg/api/plugins.go index bc38f4a7775..81b3ac10cef 100644 --- a/pkg/api/plugins.go +++ b/pkg/api/plugins.go @@ -78,48 +78,48 @@ func GetPluginList(c *m.ReqContext) Response { return Json(200, result) } -func GetPluginSettingById(c *m.ReqContext) Response { - pluginId := c.Params(":pluginId") +func GetPluginSettingByID(c *m.ReqContext) Response { + 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) - } else { - - dto := &dtos.PluginSetting{ - Type: def.Type, - Id: def.Id, - Name: def.Name, - Info: &def.Info, - Dependencies: &def.Dependencies, - Includes: def.Includes, - BaseUrl: def.BaseUrl, - Module: def.Module, - DefaultNavUrl: def.DefaultNavUrl, - LatestVersion: def.GrafanaNetVersion, - HasUpdate: def.GrafanaNetHasUpdate, - State: def.State, - } - - query := m.GetPluginSettingByIdQuery{PluginId: pluginId, OrgId: c.OrgId} - if err := bus.Dispatch(&query); err != nil { - if err != m.ErrPluginSettingNotFound { - return ApiError(500, "Failed to get login settings", nil) - } - } else { - dto.Enabled = query.Result.Enabled - dto.Pinned = query.Result.Pinned - dto.JsonData = query.Result.JsonData - } - - return Json(200, dto) } + + dto := &dtos.PluginSetting{ + Type: def.Type, + Id: def.Id, + Name: def.Name, + Info: &def.Info, + Dependencies: &def.Dependencies, + Includes: def.Includes, + BaseUrl: def.BaseUrl, + Module: def.Module, + DefaultNavUrl: def.DefaultNavUrl, + LatestVersion: def.GrafanaNetVersion, + HasUpdate: def.GrafanaNetHasUpdate, + State: def.State, + } + + query := m.GetPluginSettingByIdQuery{PluginId: pluginID, OrgId: c.OrgId} + if err := bus.Dispatch(&query); err != nil { + if err != m.ErrPluginSettingNotFound { + return ApiError(500, "Failed to get login settings", nil) + } + } else { + dto.Enabled = query.Result.Enabled + dto.Pinned = query.Result.Pinned + dto.JsonData = query.Result.JsonData + } + + return Json(200, dto) } func UpdatePluginSetting(c *m.ReqContext, cmd m.UpdatePluginSettingCmd) Response { - pluginId := c.Params(":pluginId") + pluginID := c.Params(":pluginId") cmd.OrgId = c.OrgId - cmd.PluginId = pluginId + cmd.PluginId = pluginID if _, ok := plugins.Apps[cmd.PluginId]; !ok { return ApiError(404, "Plugin not installed.", nil) @@ -133,34 +133,36 @@ func UpdatePluginSetting(c *m.ReqContext, cmd m.UpdatePluginSettingCmd) 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 { return ApiError(404, notfound.Error(), nil) } return ApiError(500, "Failed to get plugin dashboards", err) - } else { - return Json(200, list) } + + return Json(200, list) } func GetPluginMarkdown(c *m.ReqContext) Response { - pluginId := c.Params(":pluginId") + pluginID := c.Params(":pluginId") 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 { return ApiError(404, notfound.Error(), nil) } return ApiError(500, "Could not get markdown file", err) - } else { - resp := Respond(200, content) - resp.Header("Content-Type", "text/plain; charset=utf-8") - return resp } + + resp := Respond(200, content) + resp.Header("Content-Type", "text/plain; charset=utf-8") + return resp } func ImportDashboard(c *m.ReqContext, apiCmd dtos.ImportDashboardCommand) Response { diff --git a/pkg/api/preferences.go b/pkg/api/preferences.go index eb0ffa14b39..2b85c3dcee1 100644 --- a/pkg/api/preferences.go +++ b/pkg/api/preferences.go @@ -24,8 +24,8 @@ func GetUserPreferences(c *m.ReqContext) Response { return getPreferencesFor(c.OrgId, c.UserId) } -func getPreferencesFor(orgId int64, userId int64) Response { - prefsQuery := m.GetPreferencesQuery{UserId: userId, OrgId: orgId} +func getPreferencesFor(orgID int64, userID int64) Response { + prefsQuery := m.GetPreferencesQuery{UserId: userID, OrgId: orgID} if err := bus.Dispatch(&prefsQuery); err != nil { return ApiError(500, "Failed to get preferences", err) @@ -45,10 +45,10 @@ func UpdateUserPreferences(c *m.ReqContext, dtoCmd dtos.UpdatePrefsCmd) Response 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{ - UserId: userId, - OrgId: orgId, + UserId: userID, + OrgId: orgID, Theme: dtoCmd.Theme, Timezone: dtoCmd.Timezone, HomeDashboardId: dtoCmd.HomeDashboardId, diff --git a/pkg/api/search.go b/pkg/api/search.go index c8a0a5592bb..8c2b708d5a2 100644 --- a/pkg/api/search.go +++ b/pkg/api/search.go @@ -25,19 +25,19 @@ func Search(c *m.ReqContext) { permission = m.PERMISSION_EDIT } - dbids := make([]int64, 0) + dbIDs := make([]int64, 0) for _, id := range c.QueryStrings("dashboardIds") { - dashboardId, err := strconv.ParseInt(id, 10, 64) + dashboardID, err := strconv.ParseInt(id, 10, 64) 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") { - folderId, err := strconv.ParseInt(id, 10, 64) + folderID, err := strconv.ParseInt(id, 10, 64) if err == nil { - folderIds = append(folderIds, folderId) + folderIDs = append(folderIDs, folderID) } } @@ -48,9 +48,9 @@ func Search(c *m.ReqContext) { Limit: limit, IsStarred: starred == "true", OrgId: c.OrgId, - DashboardIds: dbids, + DashboardIds: dbIDs, Type: dashboardType, - FolderIds: folderIds, + FolderIds: folderIDs, Permission: permission, } diff --git a/pkg/api/team.go b/pkg/api/team.go index 316adfc4e7c..13e23df27c8 100644 --- a/pkg/api/team.go +++ b/pkg/api/team.go @@ -38,7 +38,7 @@ func UpdateTeam(c *m.ReqContext, cmd m.UpdateTeamCommand) Response { } // 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 == m.ErrTeamNotFound { return ApiError(404, "Failed to delete Team. ID not found", nil) @@ -82,7 +82,7 @@ func SearchTeams(c *m.ReqContext) Response { } // 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")} if err := bus.Dispatch(&query); err != nil { diff --git a/pkg/api/user.go b/pkg/api/user.go index b8483316b9d..4469fab2d29 100644 --- a/pkg/api/user.go +++ b/pkg/api/user.go @@ -14,12 +14,12 @@ func GetSignedInUser(c *m.ReqContext) Response { } // GET /api/users/:id -func GetUserById(c *m.ReqContext) Response { +func GetUserByID(c *m.ReqContext) Response { return getUserUserProfile(c.ParamsInt64(":id")) } -func getUserUserProfile(userId int64) Response { - query := m.GetUserProfileQuery{UserId: userId} +func getUserUserProfile(userID int64) Response { + query := m.GetUserProfileQuery{UserId: userID} if err := bus.Dispatch(&query); err != nil { if err == m.ErrUserNotFound { @@ -75,14 +75,14 @@ func UpdateUser(c *m.ReqContext, cmd m.UpdateUserCommand) Response { //POST /api/users/:id/using/:orgId func UpdateUserActiveOrg(c *m.ReqContext) Response { - userId := c.ParamsInt64(":id") - orgId := c.ParamsInt64(":orgId") + userID := c.ParamsInt64(":id") + orgID := c.ParamsInt64(":orgId") - if !validateUsingOrg(userId, orgId) { + if !validateUsingOrg(userID, orgID) { 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 { return ApiError(500, "Failed to change active organization", err) @@ -116,8 +116,8 @@ func GetUserOrgList(c *m.ReqContext) Response { return getUserOrgList(c.ParamsInt64(":id")) } -func getUserOrgList(userId int64) Response { - query := m.GetUserOrgListQuery{UserId: userId} +func getUserOrgList(userID int64) Response { + query := m.GetUserOrgListQuery{UserId: userID} if err := bus.Dispatch(&query); err != nil { return ApiError(500, "Failed to get user organizations", err) @@ -126,8 +126,8 @@ func getUserOrgList(userId int64) Response { return Json(200, query.Result) } -func validateUsingOrg(userId int64, orgId int64) bool { - query := m.GetUserOrgListQuery{UserId: userId} +func validateUsingOrg(userID int64, orgID int64) bool { + query := m.GetUserOrgListQuery{UserId: userID} if err := bus.Dispatch(&query); err != nil { return false @@ -136,7 +136,7 @@ func validateUsingOrg(userId int64, orgId int64) bool { // validate that the org id in the list valid := false for _, other := range query.Result { - if other.OrgId == orgId { + if other.OrgId == orgID { valid = true } } @@ -146,13 +146,13 @@ func validateUsingOrg(userId int64, orgId int64) bool { // POST /api/user/using/:id 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) } - cmd := m.SetUsingOrgCommand{UserId: c.UserId, OrgId: orgId} + cmd := m.SetUsingOrgCommand{UserId: c.UserId, OrgId: orgID} if err := bus.Dispatch(&cmd); err != nil { return ApiError(500, "Failed to change active organization", err) @@ -163,13 +163,13 @@ func UserSetUsingOrg(c *m.ReqContext) Response { // GET /profile/switch-org/:id 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) } - cmd := m.SetUsingOrgCommand{UserId: c.UserId, OrgId: orgId} + cmd := m.SetUsingOrgCommand{UserId: c.UserId, OrgId: orgID} if err := bus.Dispatch(&cmd); err != nil { NotFoundHandler(c) diff --git a/pkg/cmd/grafana-server/server.go b/pkg/cmd/grafana-server/server.go index 8ed3196e4ad..0338b3d6aa2 100644 --- a/pkg/cmd/grafana-server/server.go +++ b/pkg/cmd/grafana-server/server.go @@ -120,7 +120,7 @@ func (g *GrafanaServerImpl) initLogging() { } func (g *GrafanaServerImpl) startHttpServer() error { - g.httpServer = api.NewHttpServer() + g.httpServer = api.NewHTTPServer() err := g.httpServer.Start(g.context) diff --git a/pkg/middleware/auth.go b/pkg/middleware/auth.go index d6c377bc9ac..37e79c01071 100644 --- a/pkg/middleware/auth.go +++ b/pkg/middleware/auth.go @@ -17,10 +17,10 @@ type AuthOptions struct { } 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 { - return userId.(int64) + if userID != nil { + return userID.(int64) } return 0 diff --git a/pkg/middleware/dashboard_redirect.go b/pkg/middleware/dashboard_redirect.go index 7c2af548a8f..024b112e154 100644 --- a/pkg/middleware/dashboard_redirect.go +++ b/pkg/middleware/dashboard_redirect.go @@ -20,7 +20,7 @@ func getDashboardUrlBySlug(orgId int64, slug string) (string, error) { return m.GetDashboardUrl(query.Result.Uid, query.Result.Slug), nil } -func RedirectFromLegacyDashboardUrl() macaron.Handler { +func RedirectFromLegacyDashboardURL() macaron.Handler { return func(c *m.ReqContext) { slug := c.Params("slug") diff --git a/pkg/middleware/dashboard_redirect_test.go b/pkg/middleware/dashboard_redirect_test.go index 0af06347ed0..24eab2d7b79 100644 --- a/pkg/middleware/dashboard_redirect_test.go +++ b/pkg/middleware/dashboard_redirect_test.go @@ -13,7 +13,7 @@ import ( func TestMiddlewareDashboardRedirect(t *testing.T) { Convey("Given the dashboard redirect middleware", t, func() { bus.ClearBusHandlers() - redirectFromLegacyDashboardUrl := RedirectFromLegacyDashboardUrl() + redirectFromLegacyDashboardUrl := RedirectFromLegacyDashboardURL() redirectFromLegacyDashboardSoloUrl := RedirectFromLegacyDashboardSoloUrl() fakeDash := m.NewDashboard("Child dash") @@ -34,9 +34,9 @@ func TestMiddlewareDashboardRedirect(t *testing.T) { Convey("Should redirect to new dashboard url with a 301 Moved Permanently", func() { So(sc.resp.Code, ShouldEqual, 301) - redirectUrl, _ := sc.resp.Result().Location() - So(redirectUrl.Path, ShouldEqual, m.GetDashboardUrl(fakeDash.Uid, fakeDash.Slug)) - So(len(redirectUrl.Query()), ShouldEqual, 2) + redirectURL, _ := sc.resp.Result().Location() + So(redirectURL.Path, ShouldEqual, m.GetDashboardUrl(fakeDash.Uid, fakeDash.Slug)) + So(len(redirectURL.Query()), ShouldEqual, 2) }) }) @@ -47,11 +47,11 @@ func TestMiddlewareDashboardRedirect(t *testing.T) { Convey("Should redirect to new dashboard url with a 301 Moved Permanently", func() { So(sc.resp.Code, ShouldEqual, 301) - redirectUrl, _ := sc.resp.Result().Location() - expectedUrl := m.GetDashboardUrl(fakeDash.Uid, fakeDash.Slug) - expectedUrl = strings.Replace(expectedUrl, "/d/", "/d-solo/", 1) - So(redirectUrl.Path, ShouldEqual, expectedUrl) - So(len(redirectUrl.Query()), ShouldEqual, 2) + redirectURL, _ := sc.resp.Result().Location() + expectedURL := m.GetDashboardUrl(fakeDash.Uid, fakeDash.Slug) + expectedURL = strings.Replace(expectedURL, "/d/", "/d-solo/", 1) + So(redirectURL.Path, ShouldEqual, expectedURL) + So(len(redirectURL.Query()), ShouldEqual, 2) }) }) }) diff --git a/pkg/middleware/recovery_test.go b/pkg/middleware/recovery_test.go index c63a0e81e57..4bbedbc3b21 100644 --- a/pkg/middleware/recovery_test.go +++ b/pkg/middleware/recovery_test.go @@ -14,10 +14,10 @@ import ( func TestRecoveryMiddleware(t *testing.T) { Convey("Given an api route that panics", t, func() { - apiUrl := "/api/whatever" - recoveryScenario("recovery middleware should return json", apiUrl, func(sc *scenarioContext) { + apiURL := "/api/whatever" + recoveryScenario("recovery middleware should return json", apiURL, func(sc *scenarioContext) { sc.handlerFunc = PanicHandler - sc.fakeReq("GET", apiUrl).exec() + sc.fakeReq("GET", apiURL).exec() sc.req.Header.Add("content-type", "application/json") So(sc.resp.Code, ShouldEqual, 500) @@ -27,10 +27,10 @@ func TestRecoveryMiddleware(t *testing.T) { }) Convey("Given a non-api route that panics", t, func() { - apiUrl := "/whatever" - recoveryScenario("recovery middleware should return html", apiUrl, func(sc *scenarioContext) { + apiURL := "/whatever" + recoveryScenario("recovery middleware should return html", apiURL, func(sc *scenarioContext) { sc.handlerFunc = PanicHandler - sc.fakeReq("GET", apiUrl).exec() + sc.fakeReq("GET", apiURL).exec() So(sc.resp.Code, ShouldEqual, 500) So(sc.resp.Header().Get("content-type"), ShouldEqual, "text/html; charset=UTF-8")