diff --git a/pkg/api/avatar/avatar.go b/pkg/api/avatar/avatar.go index 9f282794076..5becf90ca35 100644 --- a/pkg/api/avatar/avatar.go +++ b/pkg/api/avatar/avatar.go @@ -226,7 +226,7 @@ func (this *thunderTask) Fetch() { this.Done() } -var client *http.Client = &http.Client{ +var client = &http.Client{ Timeout: time.Second * 2, Transport: &http.Transport{Proxy: http.ProxyFromEnvironment}, } diff --git a/pkg/bus/bus.go b/pkg/bus/bus.go index 437796991a5..32a591b6672 100644 --- a/pkg/bus/bus.go +++ b/pkg/bus/bus.go @@ -61,9 +61,8 @@ func (b *InProcBus) DispatchCtx(ctx context.Context, msg Msg) error { err := ret[0].Interface() if err == nil { return nil - } else { - return err.(error) } + return err.(error) } func (b *InProcBus) Dispatch(msg Msg) error { @@ -81,9 +80,8 @@ func (b *InProcBus) Dispatch(msg Msg) error { err := ret[0].Interface() if err == nil { return nil - } else { - return err.(error) } + return err.(error) } func (b *InProcBus) Publish(msg Msg) error { diff --git a/pkg/components/dynmap/dynmap.go b/pkg/components/dynmap/dynmap.go index 2b86ce384eb..96effb24332 100644 --- a/pkg/components/dynmap/dynmap.go +++ b/pkg/components/dynmap/dynmap.go @@ -134,9 +134,8 @@ func (v *Value) get(key string) (*Value, error) { child, ok := obj.Map()[key] if ok { return child, nil - } else { - return nil, KeyNotFoundError{key} } + return nil, KeyNotFoundError{key} } return nil, err @@ -174,17 +173,13 @@ func (v *Object) GetObject(keys ...string) (*Object, error) { if err != nil { return nil, err - } else { - - obj, err := child.Object() - - if err != nil { - return nil, err - } else { - return obj, nil - } - } + obj, err := child.Object() + + if err != nil { + return nil, err + } + return obj, nil } // Gets the value at key path and attempts to typecast the value into a string. @@ -196,18 +191,17 @@ func (v *Object) GetString(keys ...string) (string, error) { if err != nil { return "", err - } else { - return child.String() } + return child.String() } func (v *Object) MustGetString(path string, def string) string { keys := strings.Split(path, ".") - if str, err := v.GetString(keys...); err != nil { + str, err := v.GetString(keys...) + if err != nil { return def - } else { - return str } + return str } // Gets the value at key path and attempts to typecast the value into null. @@ -233,16 +227,13 @@ func (v *Object) GetNumber(keys ...string) (json.Number, error) { if err != nil { return "", err - } else { - - n, err := child.Number() - - if err != nil { - return "", err - } else { - return n, nil - } } + n, err := child.Number() + + if err != nil { + return "", err + } + return n, nil } // Gets the value at key path and attempts to typecast the value into a float64. @@ -254,16 +245,13 @@ func (v *Object) GetFloat64(keys ...string) (float64, error) { if err != nil { return 0, err - } else { - - n, err := child.Float64() - - if err != nil { - return 0, err - } else { - return n, nil - } } + n, err := child.Float64() + + if err != nil { + return 0, err + } + return n, nil } // Gets the value at key path and attempts to typecast the value into a float64. @@ -275,16 +263,13 @@ func (v *Object) GetInt64(keys ...string) (int64, error) { if err != nil { return 0, err - } else { - - n, err := child.Int64() - - if err != nil { - return 0, err - } else { - return n, nil - } } + n, err := child.Int64() + + if err != nil { + return 0, err + } + return n, nil } // Gets the value at key path and attempts to typecast the value into a float64. @@ -296,9 +281,8 @@ func (v *Object) GetInterface(keys ...string) (interface{}, error) { if err != nil { return nil, err - } else { - return child.Interface(), nil } + return child.Interface(), nil } // Gets the value at key path and attempts to typecast the value into a bool. @@ -311,7 +295,6 @@ func (v *Object) GetBoolean(keys ...string) (bool, error) { if err != nil { return false, err } - return child.Boolean() } @@ -328,11 +311,8 @@ func (v *Object) GetValueArray(keys ...string) ([]*Value, error) { if err != nil { return nil, err - } else { - - return child.Array() - } + return child.Array() } // Gets the value at key path and attempts to typecast the value into an array of objects. @@ -347,30 +327,24 @@ func (v *Object) GetObjectArray(keys ...string) ([]*Object, error) { if err != nil { return nil, err - } else { + } + array, err := child.Array() - array, err := child.Array() + if err != nil { + return nil, err + } + typedArray := make([]*Object, len(array)) + + for index, arrayItem := range array { + typedArrayItem, err := arrayItem. + Object() if err != nil { return nil, err - } else { - - typedArray := make([]*Object, len(array)) - - for index, arrayItem := range array { - typedArrayItem, err := arrayItem. - Object() - - if err != nil { - return nil, err - } else { - typedArray[index] = typedArrayItem - } - - } - return typedArray, nil } + typedArray[index] = typedArrayItem } + return typedArray, nil } // Gets the value at key path and attempts to typecast the value into an array of string. @@ -387,29 +361,23 @@ func (v *Object) GetStringArray(keys ...string) ([]string, error) { if err != nil { return nil, err - } else { + } + array, err := child.Array() - array, err := child.Array() + if err != nil { + return nil, err + } + typedArray := make([]string, len(array)) + + for index, arrayItem := range array { + typedArrayItem, err := arrayItem.String() if err != nil { return nil, err - } else { - - typedArray := make([]string, len(array)) - - for index, arrayItem := range array { - typedArrayItem, err := arrayItem.String() - - if err != nil { - return nil, err - } else { - typedArray[index] = typedArrayItem - } - - } - return typedArray, nil } + typedArray[index] = typedArrayItem } + return typedArray, nil } // Gets the value at key path and attempts to typecast the value into an array of numbers. @@ -424,29 +392,23 @@ func (v *Object) GetNumberArray(keys ...string) ([]json.Number, error) { if err != nil { return nil, err - } else { + } + array, err := child.Array() - array, err := child.Array() + if err != nil { + return nil, err + } + typedArray := make([]json.Number, len(array)) + + for index, arrayItem := range array { + typedArrayItem, err := arrayItem.Number() if err != nil { return nil, err - } else { - - typedArray := make([]json.Number, len(array)) - - for index, arrayItem := range array { - typedArrayItem, err := arrayItem.Number() - - if err != nil { - return nil, err - } else { - typedArray[index] = typedArrayItem - } - - } - return typedArray, nil } + typedArray[index] = typedArrayItem } + return typedArray, nil } // Gets the value at key path and attempts to typecast the value into an array of floats. @@ -456,29 +418,23 @@ func (v *Object) GetFloat64Array(keys ...string) ([]float64, error) { if err != nil { return nil, err - } else { + } + array, err := child.Array() - array, err := child.Array() + if err != nil { + return nil, err + } + typedArray := make([]float64, len(array)) + + for index, arrayItem := range array { + typedArrayItem, err := arrayItem.Float64() if err != nil { return nil, err - } else { - - typedArray := make([]float64, len(array)) - - for index, arrayItem := range array { - typedArrayItem, err := arrayItem.Float64() - - if err != nil { - return nil, err - } else { - typedArray[index] = typedArrayItem - } - - } - return typedArray, nil } + typedArray[index] = typedArrayItem } + return typedArray, nil } // Gets the value at key path and attempts to typecast the value into an array of ints. @@ -488,29 +444,23 @@ func (v *Object) GetInt64Array(keys ...string) ([]int64, error) { if err != nil { return nil, err - } else { + } + array, err := child.Array() - array, err := child.Array() + if err != nil { + return nil, err + } + typedArray := make([]int64, len(array)) + + for index, arrayItem := range array { + typedArrayItem, err := arrayItem.Int64() if err != nil { return nil, err - } else { - - typedArray := make([]int64, len(array)) - - for index, arrayItem := range array { - typedArrayItem, err := arrayItem.Int64() - - if err != nil { - return nil, err - } else { - typedArray[index] = typedArrayItem - } - - } - return typedArray, nil } + typedArray[index] = typedArrayItem } + return typedArray, nil } // Gets the value at key path and attempts to typecast the value into an array of bools. @@ -520,29 +470,23 @@ func (v *Object) GetBooleanArray(keys ...string) ([]bool, error) { if err != nil { return nil, err - } else { + } + array, err := child.Array() - array, err := child.Array() + if err != nil { + return nil, err + } + typedArray := make([]bool, len(array)) + + for index, arrayItem := range array { + typedArrayItem, err := arrayItem.Boolean() if err != nil { return nil, err - } else { - - typedArray := make([]bool, len(array)) - - for index, arrayItem := range array { - typedArrayItem, err := arrayItem.Boolean() - - if err != nil { - return nil, err - } else { - typedArray[index] = typedArrayItem - } - - } - return typedArray, nil } + typedArray[index] = typedArrayItem } + return typedArray, nil } // Gets the value at key path and attempts to typecast the value into an array of nulls. @@ -552,29 +496,23 @@ func (v *Object) GetNullArray(keys ...string) (int64, error) { if err != nil { return 0, err - } else { + } + array, err := child.Array() - array, err := child.Array() + if err != nil { + return 0, err + } + var length int64 = 0 + + for _, arrayItem := range array { + err := arrayItem.Null() if err != nil { return 0, err - } else { - - var length int64 = 0 - - for _, arrayItem := range array { - err := arrayItem.Null() - - if err != nil { - return 0, err - } else { - length++ - } - - } - return length, nil } + length++ } + return length, nil } // Returns an error if the value is not actually null @@ -590,9 +528,7 @@ func (v *Value) Null() error { if valid { return nil } - return ErrNotNull - } // Attempts to typecast the current value into an array. @@ -612,17 +548,13 @@ func (v *Value) Array() ([]*Value, error) { var slice []*Value if valid { - for _, element := range v.data.([]interface{}) { child := Value{element, true} slice = append(slice, &child) } - return slice, nil } - return slice, ErrNotArray - } // Attempts to typecast the current value into a number. diff --git a/pkg/login/brute_force_login_protection.go b/pkg/login/brute_force_login_protection.go index ca5e0a667ff..d524c420540 100644 --- a/pkg/login/brute_force_login_protection.go +++ b/pkg/login/brute_force_login_protection.go @@ -9,8 +9,8 @@ import ( ) var ( - maxInvalidLoginAttempts int64 = 5 - loginAttemptsWindow time.Duration = time.Minute * 5 + maxInvalidLoginAttempts int64 = 5 + loginAttemptsWindow = time.Minute * 5 ) var validateLoginAttempts = func(username string) error { diff --git a/pkg/login/ldap.go b/pkg/login/ldap.go index de530c0cf63..49b92648561 100644 --- a/pkg/login/ldap.go +++ b/pkg/login/ldap.go @@ -50,12 +50,12 @@ func (a *ldapAuther) Dial() error { if a.server.RootCACert != "" { certPool = x509.NewCertPool() for _, caCertFile := range strings.Split(a.server.RootCACert, " ") { - if pem, err := ioutil.ReadFile(caCertFile); err != nil { + pem, err := ioutil.ReadFile(caCertFile) + if err != nil { return err - } else { - if !certPool.AppendCertsFromPEM(pem) { - return errors.New("Failed to append CA certificate " + caCertFile) - } + } + if !certPool.AppendCertsFromPEM(pem) { + return errors.New("Failed to append CA certificate " + caCertFile) } } } diff --git a/pkg/login/ldap_test.go b/pkg/login/ldap_test.go index 6085fffb638..b8ef261c815 100644 --- a/pkg/login/ldap_test.go +++ b/pkg/login/ldap_test.go @@ -369,10 +369,9 @@ func (sc *scenarioContext) userQueryReturns(user *m.User) { bus.AddHandler("test", func(query *m.GetUserByAuthInfoQuery) error { if user == nil { return m.ErrUserNotFound - } else { - query.Result = user - return nil } + query.Result = user + return nil }) bus.AddHandler("test", func(query *m.SetAuthInfoCommand) error { return nil diff --git a/pkg/metrics/graphitebridge/graphite.go b/pkg/metrics/graphitebridge/graphite.go index 670636cedce..5b61f078e6c 100644 --- a/pkg/metrics/graphitebridge/graphite.go +++ b/pkg/metrics/graphitebridge/graphite.go @@ -55,7 +55,7 @@ const ( AbortOnError ) -var metricCategoryPrefix []string = []string{ +var metricCategoryPrefix = []string{ "proxy_", "api_", "page_", @@ -66,7 +66,7 @@ var metricCategoryPrefix []string = []string{ "go_", "process_"} -var trimMetricPrefix []string = []string{"grafana_"} +var trimMetricPrefix = []string{"grafana_"} // Config defines the Graphite bridge config. type Config struct { diff --git a/pkg/middleware/middleware_test.go b/pkg/middleware/middleware_test.go index 072cb793d3c..b827751b1a5 100644 --- a/pkg/middleware/middleware_test.go +++ b/pkg/middleware/middleware_test.go @@ -210,9 +210,8 @@ func TestMiddlewareContext(t *testing.T) { if query.UserId > 0 { query.Result = &m.SignedInUser{OrgId: 4, UserId: 33} return nil - } else { - return m.ErrUserNotFound } + return m.ErrUserNotFound }) bus.AddHandler("test", func(cmd *m.UpsertUserCommand) error { diff --git a/pkg/models/alert.go b/pkg/models/alert.go index 88b49350b97..b72d87e94b2 100644 --- a/pkg/models/alert.go +++ b/pkg/models/alert.go @@ -34,8 +34,8 @@ const ( ) var ( - ErrCannotChangeStateOnPausedAlert error = fmt.Errorf("Cannot change state on pause alert") - ErrRequiresNewState error = fmt.Errorf("update alert state requires a new state.") + ErrCannotChangeStateOnPausedAlert = fmt.Errorf("Cannot change state on pause alert") + ErrRequiresNewState = fmt.Errorf("update alert state requires a new state.") ) func (s AlertStateType) IsValid() bool { diff --git a/pkg/models/datasource.go b/pkg/models/datasource.go index f2236ad8477..b7e3e3eaa17 100644 --- a/pkg/models/datasource.go +++ b/pkg/models/datasource.go @@ -58,7 +58,7 @@ type DataSource struct { Updated time.Time } -var knownDatasourcePlugins map[string]bool = map[string]bool{ +var knownDatasourcePlugins = map[string]bool{ DS_ES: true, DS_GRAPHITE: true, DS_INFLUXDB: true, diff --git a/pkg/plugins/dashboard_importer.go b/pkg/plugins/dashboard_importer.go index fb4d63a1fe4..1364fded987 100644 --- a/pkg/plugins/dashboard_importer.go +++ b/pkg/plugins/dashboard_importer.go @@ -148,11 +148,11 @@ func (this *DashTemplateEvaluator) evalValue(source *simplejson.Json) interface{ switch v := sourceValue.(type) { case string: interpolated := this.varRegex.ReplaceAllStringFunc(v, func(match string) string { - if replacement, exists := this.variables[match]; exists { + replacement, exists := this.variables[match] + if exists { return replacement - } else { - return match } + return match }) return interpolated case bool: diff --git a/pkg/plugins/dashboards_updater.go b/pkg/plugins/dashboards_updater.go index 04d3dc035cc..ebe11ed32d4 100644 --- a/pkg/plugins/dashboards_updater.go +++ b/pkg/plugins/dashboards_updater.go @@ -34,23 +34,24 @@ func (pm *PluginManager) updateAppDashboards() { } func autoUpdateAppDashboard(pluginDashInfo *PluginDashboardInfoDTO, orgId int64) error { - if dash, err := loadPluginDashboard(pluginDashInfo.PluginId, pluginDashInfo.Path); err != nil { + dash, err := loadPluginDashboard(pluginDashInfo.PluginId, pluginDashInfo.Path) + if err != nil { return err - } else { - plog.Info("Auto updating App dashboard", "dashboard", dash.Title, "newRev", pluginDashInfo.Revision, "oldRev", pluginDashInfo.ImportedRevision) - updateCmd := ImportDashboardCommand{ - OrgId: orgId, - PluginId: pluginDashInfo.PluginId, - Overwrite: true, - Dashboard: dash.Data, - User: &m.SignedInUser{UserId: 0, OrgRole: m.ROLE_ADMIN}, - Path: pluginDashInfo.Path, - } - - if err := bus.Dispatch(&updateCmd); err != nil { - return err - } } + plog.Info("Auto updating App dashboard", "dashboard", dash.Title, "newRev", pluginDashInfo.Revision, "oldRev", pluginDashInfo.ImportedRevision) + updateCmd := ImportDashboardCommand{ + OrgId: orgId, + PluginId: pluginDashInfo.PluginId, + Overwrite: true, + Dashboard: dash.Data, + User: &m.SignedInUser{UserId: 0, OrgRole: m.ROLE_ADMIN}, + Path: pluginDashInfo.Path, + } + + if err := bus.Dispatch(&updateCmd); err != nil { + return err + } + return nil } @@ -118,15 +119,14 @@ func handlePluginStateChanged(event *m.PluginStateChangedEvent) error { if err := bus.Dispatch(&query); err != nil { return err - } else { - for _, dash := range query.Result { - deleteCmd := m.DeleteDashboardCommand{OrgId: dash.OrgId, Id: dash.Id} + } + for _, dash := range query.Result { + deleteCmd := m.DeleteDashboardCommand{OrgId: dash.OrgId, Id: dash.Id} - plog.Info("Deleting plugin dashboard", "pluginId", event.PluginId, "dashboard", dash.Slug) + plog.Info("Deleting plugin dashboard", "pluginId", event.PluginId, "dashboard", dash.Slug) - if err := bus.Dispatch(&deleteCmd); err != nil { - return err - } + if err := bus.Dispatch(&deleteCmd); err != nil { + return err } } } diff --git a/pkg/plugins/plugins.go b/pkg/plugins/plugins.go index 8ccdb9cf18b..aa4131ae06d 100644 --- a/pkg/plugins/plugins.go +++ b/pkg/plugins/plugins.go @@ -205,11 +205,11 @@ func (scanner *PluginScanner) loadPluginJson(pluginJsonFilePath string) error { } var loader PluginLoader - if pluginGoType, exists := PluginTypes[pluginCommon.Type]; !exists { + pluginGoType, exists := PluginTypes[pluginCommon.Type] + if !exists { return errors.New("Unknown plugin type " + pluginCommon.Type) - } else { - loader = reflect.New(reflect.TypeOf(pluginGoType)).Interface().(PluginLoader) } + loader = reflect.New(reflect.TypeOf(pluginGoType)).Interface().(PluginLoader) reader.Seek(0, 0) return loader.Load(jsonParser, currentDir) @@ -230,9 +230,9 @@ func GetPluginMarkdown(pluginId string, name string) ([]byte, error) { return make([]byte, 0), nil } - if data, err := ioutil.ReadFile(path); err != nil { + data, err := ioutil.ReadFile(path) + if err != nil { return nil, err - } else { - return data, nil } + return data, nil } diff --git a/pkg/plugins/update_checker.go b/pkg/plugins/update_checker.go index 57f6d2ca651..e61f4cf1df7 100644 --- a/pkg/plugins/update_checker.go +++ b/pkg/plugins/update_checker.go @@ -13,7 +13,7 @@ import ( ) var ( - httpClient http.Client = http.Client{Timeout: 10 * time.Second} + httpClient = http.Client{Timeout: 10 * time.Second} ) type GrafanaNetPlugin struct { diff --git a/pkg/services/alerting/conditions/evaluator.go b/pkg/services/alerting/conditions/evaluator.go index dfc058940cf..8d7ca57f010 100644 --- a/pkg/services/alerting/conditions/evaluator.go +++ b/pkg/services/alerting/conditions/evaluator.go @@ -9,8 +9,8 @@ import ( ) var ( - defaultTypes []string = []string{"gt", "lt"} - rangedTypes []string = []string{"within_range", "outside_range"} + defaultTypes = []string{"gt", "lt"} + rangedTypes = []string{"within_range", "outside_range"} ) type AlertEvaluator interface { diff --git a/pkg/services/alerting/engine.go b/pkg/services/alerting/engine.go index bdd8ff2cfe2..ddc91c0eb10 100644 --- a/pkg/services/alerting/engine.go +++ b/pkg/services/alerting/engine.go @@ -100,10 +100,10 @@ func (e *Engine) runJobDispatcher(grafanaCtx context.Context) error { } var ( - unfinishedWorkTimeout time.Duration = time.Second * 5 + unfinishedWorkTimeout = time.Second * 5 // TODO: Make alertTimeout and alertMaxAttempts configurable in the config file. - alertTimeout time.Duration = time.Second * 30 - alertMaxAttempts int = 3 + alertTimeout = time.Second * 30 + alertMaxAttempts = 3 ) func (e *Engine) processJobWithRetry(grafanaCtx context.Context, job *Job) error { diff --git a/pkg/services/alerting/eval_context.go b/pkg/services/alerting/eval_context.go index 91d0e179a14..d0441d379b7 100644 --- a/pkg/services/alerting/eval_context.go +++ b/pkg/services/alerting/eval_context.go @@ -106,11 +106,11 @@ func (c *EvalContext) GetRuleUrl() (string, error) { return setting.AppUrl, nil } - if ref, err := c.GetDashboardUID(); err != nil { + ref, err := c.GetDashboardUID() + if err != nil { return "", err - } else { - return fmt.Sprintf(urlFormat, m.GetFullDashboardUrl(ref.Uid, ref.Slug), c.Rule.PanelId, c.Rule.OrgId), nil } + return fmt.Sprintf(urlFormat, m.GetFullDashboardUrl(ref.Uid, ref.Slug), c.Rule.PanelId, c.Rule.OrgId), nil } func (c *EvalContext) GetNewState() m.AlertStateType { diff --git a/pkg/services/alerting/notifier.go b/pkg/services/alerting/notifier.go index af9ba52a52a..1d5affbd3ec 100644 --- a/pkg/services/alerting/notifier.go +++ b/pkg/services/alerting/notifier.go @@ -87,17 +87,17 @@ func (n *notificationService) uploadImage(context *EvalContext) (err error) { IsAlertContext: true, } - if ref, err := context.GetDashboardUID(); err != nil { + ref, err := context.GetDashboardUID() + if err != nil { return err - } else { - renderOpts.Path = fmt.Sprintf("d-solo/%s/%s?panelId=%d", ref.Uid, ref.Slug, context.Rule.PanelId) } + renderOpts.Path = fmt.Sprintf("d-solo/%s/%s?panelId=%d", ref.Uid, ref.Slug, context.Rule.PanelId) - if imagePath, err := renderer.RenderToPng(renderOpts); err != nil { + imagePath, err := renderer.RenderToPng(renderOpts) + if err != nil { return err - } else { - context.ImageOnDiskPath = imagePath } + context.ImageOnDiskPath = imagePath context.ImagePublicUrl, err = uploader.Upload(context.Ctx, context.ImageOnDiskPath) if err != nil { @@ -117,12 +117,12 @@ func (n *notificationService) getNeededNotifiers(orgId int64, notificationIds [] var result []Notifier for _, notification := range query.Result { - if not, err := n.createNotifierFor(notification); err != nil { + not, err := n.createNotifierFor(notification) + if err != nil { return nil, err - } else { - if not.ShouldNotify(context) { - result = append(result, not) - } + } + if not.ShouldNotify(context) { + result = append(result, not) } } @@ -140,7 +140,7 @@ func (n *notificationService) createNotifierFor(model *m.AlertNotification) (Not type NotifierFactory func(notification *m.AlertNotification) (Notifier, error) -var notifierFactories map[string]*NotifierPlugin = make(map[string]*NotifierPlugin) +var notifierFactories = make(map[string]*NotifierPlugin) func RegisterNotifier(plugin *NotifierPlugin) { notifierFactories[plugin.Type] = plugin diff --git a/pkg/services/alerting/notifiers/opsgenie.go b/pkg/services/alerting/notifiers/opsgenie.go index 5d8b15160c4..f0f5142cf05 100644 --- a/pkg/services/alerting/notifiers/opsgenie.go +++ b/pkg/services/alerting/notifiers/opsgenie.go @@ -41,7 +41,7 @@ func init() { } var ( - opsgenieAlertURL string = "https://api.opsgenie.com/v2/alerts" + opsgenieAlertURL = "https://api.opsgenie.com/v2/alerts" ) func NewOpsGenieNotifier(model *m.AlertNotification) (alerting.Notifier, error) { diff --git a/pkg/services/alerting/notifiers/pagerduty.go b/pkg/services/alerting/notifiers/pagerduty.go index 58484051432..02219b2203d 100644 --- a/pkg/services/alerting/notifiers/pagerduty.go +++ b/pkg/services/alerting/notifiers/pagerduty.go @@ -40,7 +40,7 @@ func init() { } var ( - pagerdutyEventApiUrl string = "https://events.pagerduty.com/v2/enqueue" + pagerdutyEventApiUrl = "https://events.pagerduty.com/v2/enqueue" ) func NewPagerdutyNotifier(model *m.AlertNotification) (alerting.Notifier, error) { diff --git a/pkg/services/alerting/notifiers/telegram.go b/pkg/services/alerting/notifiers/telegram.go index 1e62c68d7eb..ca24c996914 100644 --- a/pkg/services/alerting/notifiers/telegram.go +++ b/pkg/services/alerting/notifiers/telegram.go @@ -18,7 +18,7 @@ const ( ) var ( - telegramApiUrl string = "https://api.telegram.org/bot%s/%s" + telegramApiUrl = "https://api.telegram.org/bot%s/%s" ) func init() { @@ -91,9 +91,8 @@ func (this *TelegramNotifier) buildMessage(evalContext *alerting.EvalContext, se cmd, err := this.buildMessageInlineImage(evalContext) if err == nil { return cmd - } else { - this.log.Error("Could not generate Telegram message with inline image.", "err", err) } + this.log.Error("Could not generate Telegram message with inline image.", "err", err) } return this.buildMessageLinkedImage(evalContext) diff --git a/pkg/services/alerting/rule.go b/pkg/services/alerting/rule.go index 027ff96d6c0..018d138dbe4 100644 --- a/pkg/services/alerting/rule.go +++ b/pkg/services/alerting/rule.go @@ -103,25 +103,25 @@ func NewRuleFromDBAlert(ruleDef *m.Alert) (*Rule, error) { for _, v := range ruleDef.Settings.Get("notifications").MustArray() { jsonModel := simplejson.NewFromAny(v) - if id, err := jsonModel.Get("id").Int64(); err != nil { + id, err := jsonModel.Get("id").Int64() + if err != nil { return nil, ValidationError{Reason: "Invalid notification schema", DashboardId: model.DashboardId, Alertid: model.Id, PanelId: model.PanelId} - } else { - model.Notifications = append(model.Notifications, id) } + model.Notifications = append(model.Notifications, id) } for index, condition := range ruleDef.Settings.Get("conditions").MustArray() { conditionModel := simplejson.NewFromAny(condition) conditionType := conditionModel.Get("type").MustString() - if factory, exist := conditionFactories[conditionType]; !exist { + factory, exist := conditionFactories[conditionType] + if !exist { return nil, ValidationError{Reason: "Unknown alert condition: " + conditionType, DashboardId: model.DashboardId, Alertid: model.Id, PanelId: model.PanelId} - } else { - if queryCondition, err := factory(conditionModel, index); err != nil { - return nil, ValidationError{Err: err, DashboardId: model.DashboardId, Alertid: model.Id, PanelId: model.PanelId} - } else { - model.Conditions = append(model.Conditions, queryCondition) - } } + queryCondition, err := factory(conditionModel, index) + if err != nil { + return nil, ValidationError{Err: err, DashboardId: model.DashboardId, Alertid: model.Id, PanelId: model.PanelId} + } + model.Conditions = append(model.Conditions, queryCondition) } if len(model.Conditions) == 0 { @@ -133,7 +133,7 @@ func NewRuleFromDBAlert(ruleDef *m.Alert) (*Rule, error) { type ConditionFactory func(model *simplejson.Json, index int) (Condition, error) -var conditionFactories map[string]ConditionFactory = make(map[string]ConditionFactory) +var conditionFactories = make(map[string]ConditionFactory) func RegisterCondition(typeName string, factory ConditionFactory) { conditionFactories[typeName] = factory diff --git a/pkg/services/provisioning/dashboards/config_reader_test.go b/pkg/services/provisioning/dashboards/config_reader_test.go index ecbf6435c36..72664c37990 100644 --- a/pkg/services/provisioning/dashboards/config_reader_test.go +++ b/pkg/services/provisioning/dashboards/config_reader_test.go @@ -8,9 +8,9 @@ import ( ) var ( - simpleDashboardConfig string = "./test-configs/dashboards-from-disk" - oldVersion string = "./test-configs/version-0" - brokenConfigs string = "./test-configs/broken-configs" + simpleDashboardConfig = "./test-configs/dashboards-from-disk" + oldVersion = "./test-configs/version-0" + brokenConfigs = "./test-configs/broken-configs" ) func TestDashboardsAsConfig(t *testing.T) { diff --git a/pkg/services/provisioning/dashboards/file_reader.go b/pkg/services/provisioning/dashboards/file_reader.go index 7d4231deeae..e5186e12f06 100644 --- a/pkg/services/provisioning/dashboards/file_reader.go +++ b/pkg/services/provisioning/dashboards/file_reader.go @@ -19,9 +19,9 @@ import ( ) var ( - checkDiskForChangesInterval time.Duration = time.Second * 3 + checkDiskForChangesInterval = time.Second * 3 - ErrFolderNameMissing error = errors.New("Folder name missing") + ErrFolderNameMissing = errors.New("Folder name missing") ) type fileReader struct { diff --git a/pkg/services/provisioning/datasources/config_reader_test.go b/pkg/services/provisioning/datasources/config_reader_test.go index 7d621ffe70f..89ecc5a0b68 100644 --- a/pkg/services/provisioning/datasources/config_reader_test.go +++ b/pkg/services/provisioning/datasources/config_reader_test.go @@ -11,13 +11,14 @@ import ( ) var ( - logger log.Logger = log.New("fake.log") - twoDatasourcesConfig string = "./test-configs/two-datasources" - twoDatasourcesConfigPurgeOthers string = "./test-configs/insert-two-delete-two" - doubleDatasourcesConfig string = "./test-configs/double-default" - allProperties string = "./test-configs/all-properties" - versionZero string = "./test-configs/version-0" - brokenYaml string = "./test-configs/broken-yaml" + logger log.Logger = log.New("fake.log") + + twoDatasourcesConfig = "./test-configs/two-datasources" + twoDatasourcesConfigPurgeOthers = "./test-configs/insert-two-delete-two" + doubleDatasourcesConfig = "./test-configs/double-default" + allProperties = "./test-configs/all-properties" + versionZero = "./test-configs/version-0" + brokenYaml = "./test-configs/broken-yaml" fakeRepo *fakeRepository ) diff --git a/pkg/services/sqlstore/annotation.go b/pkg/services/sqlstore/annotation.go index 1066be0ef74..1710679cea1 100644 --- a/pkg/services/sqlstore/annotation.go +++ b/pkg/services/sqlstore/annotation.go @@ -29,13 +29,13 @@ func (r *SqlAnnotationRepo) Save(item *annotations.Item) error { } if item.Tags != nil { - if tags, err := r.ensureTagsExist(sess, tags); err != nil { + tags, err := r.ensureTagsExist(sess, tags) + if err != nil { return err - } else { - for _, tag := range tags { - if _, err := sess.Exec("INSERT INTO annotation_tag (annotation_id, tag_id) VALUES(?,?)", item.Id, tag.Id); err != nil { - return err - } + } + for _, tag := range tags { + if _, err := sess.Exec("INSERT INTO annotation_tag (annotation_id, tag_id) VALUES(?,?)", item.Id, tag.Id); err != nil { + return err } } } @@ -94,17 +94,17 @@ func (r *SqlAnnotationRepo) Update(item *annotations.Item) error { } if item.Tags != nil { - if tags, err := r.ensureTagsExist(sess, models.ParseTagPairs(item.Tags)); err != nil { + tags, err := r.ensureTagsExist(sess, models.ParseTagPairs(item.Tags)) + if err != nil { return err - } else { - if _, err := sess.Exec("DELETE FROM annotation_tag WHERE annotation_id = ?", existing.Id); err != nil { + } + if _, err := sess.Exec("DELETE FROM annotation_tag WHERE annotation_id = ?", existing.Id); err != nil { + return err + } + for _, tag := range tags { + if _, err := sess.Exec("INSERT INTO annotation_tag (annotation_id, tag_id) VALUES(?,?)", existing.Id, tag.Id); err != nil { return err } - for _, tag := range tags { - if _, err := sess.Exec("INSERT INTO annotation_tag (annotation_id, tag_id) VALUES(?,?)", existing.Id, tag.Id); err != nil { - return err - } - } } } diff --git a/pkg/services/sqlstore/dashboard_test.go b/pkg/services/sqlstore/dashboard_test.go index 9124a686236..6d7c7a93e47 100644 --- a/pkg/services/sqlstore/dashboard_test.go +++ b/pkg/services/sqlstore/dashboard_test.go @@ -104,9 +104,8 @@ func TestDashboardDataAccess(t *testing.T) { timesCalled += 1 if timesCalled <= 2 { return savedDash.Uid - } else { - return util.GenerateShortUid() } + return util.GenerateShortUid() } cmd := m.SaveDashboardCommand{ OrgId: 1, diff --git a/pkg/services/sqlstore/migrator/migrator.go b/pkg/services/sqlstore/migrator/migrator.go index 0fde3f27c01..cd00cb16712 100644 --- a/pkg/services/sqlstore/migrator/migrator.go +++ b/pkg/services/sqlstore/migrator/migrator.go @@ -97,17 +97,15 @@ func (mg *Migrator) Start() error { mg.Logger.Debug("Executing", "sql", sql) err := mg.inTransaction(func(sess *xorm.Session) error { - - if err := mg.exec(m, sess); err != nil { + err := mg.exec(m, sess) + if err != nil { mg.Logger.Error("Exec failed", "error", err, "sql", sql) record.Error = err.Error() sess.Insert(&record) return err - } else { - record.Success = true - sess.Insert(&record) } - + record.Success = true + sess.Insert(&record) return nil }) diff --git a/pkg/services/sqlstore/migrator/mysql_dialect.go b/pkg/services/sqlstore/migrator/mysql_dialect.go index 1968558dbb8..300224135f0 100644 --- a/pkg/services/sqlstore/migrator/mysql_dialect.go +++ b/pkg/services/sqlstore/migrator/mysql_dialect.go @@ -66,8 +66,8 @@ func (db *Mysql) SqlType(c *Column) string { res = c.Type } - var hasLen1 bool = (c.Length > 0) - var hasLen2 bool = (c.Length2 > 0) + var hasLen1 = (c.Length > 0) + var hasLen2 = (c.Length2 > 0) if res == DB_BigInt && !hasLen1 && !hasLen2 { c.Length = 20 diff --git a/pkg/services/sqlstore/migrator/postgres_dialect.go b/pkg/services/sqlstore/migrator/postgres_dialect.go index 8de26194411..e167aa33122 100644 --- a/pkg/services/sqlstore/migrator/postgres_dialect.go +++ b/pkg/services/sqlstore/migrator/postgres_dialect.go @@ -45,9 +45,8 @@ func (b *Postgres) Default(col *Column) string { if col.Type == DB_Bool { if col.Default == "0" { return "FALSE" - } else { - return "TRUE" } + return "TRUE" } return col.Default } @@ -92,8 +91,8 @@ func (db *Postgres) SqlType(c *Column) string { res = t } - var hasLen1 bool = (c.Length > 0) - var hasLen2 bool = (c.Length2 > 0) + var hasLen1 = (c.Length > 0) + var hasLen2 = (c.Length2 > 0) if hasLen2 { res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")" } else if hasLen1 { diff --git a/pkg/services/sqlstore/plugin_setting.go b/pkg/services/sqlstore/plugin_setting.go index f694fbbd5f0..676d26fad56 100644 --- a/pkg/services/sqlstore/plugin_setting.go +++ b/pkg/services/sqlstore/plugin_setting.go @@ -75,34 +75,33 @@ func UpdatePluginSetting(cmd *m.UpdatePluginSettingCmd) error { _, err = sess.Insert(&pluginSetting) return err - } else { - for key, data := range cmd.SecureJsonData { - encryptedData, err := util.Encrypt([]byte(data), setting.SecretKey) - if err != nil { - return err - } - - pluginSetting.SecureJsonData[key] = encryptedData - } - - // add state change event on commit success - if pluginSetting.Enabled != cmd.Enabled { - sess.events = append(sess.events, &m.PluginStateChangedEvent{ - PluginId: cmd.PluginId, - OrgId: cmd.OrgId, - Enabled: cmd.Enabled, - }) - } - - pluginSetting.Updated = time.Now() - pluginSetting.Enabled = cmd.Enabled - pluginSetting.JsonData = cmd.JsonData - pluginSetting.Pinned = cmd.Pinned - pluginSetting.PluginVersion = cmd.PluginVersion - - _, err = sess.Id(pluginSetting.Id).Update(&pluginSetting) - return err } + for key, data := range cmd.SecureJsonData { + encryptedData, err := util.Encrypt([]byte(data), setting.SecretKey) + if err != nil { + return err + } + + pluginSetting.SecureJsonData[key] = encryptedData + } + + // add state change event on commit success + if pluginSetting.Enabled != cmd.Enabled { + sess.events = append(sess.events, &m.PluginStateChangedEvent{ + PluginId: cmd.PluginId, + OrgId: cmd.OrgId, + Enabled: cmd.Enabled, + }) + } + + pluginSetting.Updated = time.Now() + pluginSetting.Enabled = cmd.Enabled + pluginSetting.JsonData = cmd.JsonData + pluginSetting.Pinned = cmd.Pinned + pluginSetting.PluginVersion = cmd.PluginVersion + + _, err = sess.Id(pluginSetting.Id).Update(&pluginSetting) + return err }) } diff --git a/pkg/services/sqlstore/preferences.go b/pkg/services/sqlstore/preferences.go index a070fa621b5..885837764fc 100644 --- a/pkg/services/sqlstore/preferences.go +++ b/pkg/services/sqlstore/preferences.go @@ -88,14 +88,13 @@ func SavePreferences(cmd *m.SavePreferencesCommand) error { } _, err = sess.Insert(&prefs) return err - } else { - prefs.HomeDashboardId = cmd.HomeDashboardId - prefs.Timezone = cmd.Timezone - prefs.Theme = cmd.Theme - prefs.Updated = time.Now() - prefs.Version += 1 - _, err := sess.Id(prefs.Id).AllCols().Update(&prefs) - return err } + prefs.HomeDashboardId = cmd.HomeDashboardId + prefs.Timezone = cmd.Timezone + prefs.Theme = cmd.Theme + prefs.Updated = time.Now() + prefs.Version += 1 + _, err = sess.Id(prefs.Id).AllCols().Update(&prefs) + return err }) } diff --git a/pkg/services/sqlstore/stats.go b/pkg/services/sqlstore/stats.go index 47020d1a6f7..173a1e56634 100644 --- a/pkg/services/sqlstore/stats.go +++ b/pkg/services/sqlstore/stats.go @@ -13,7 +13,7 @@ func init() { bus.AddHandler("sql", GetAdminStats) } -var activeUserTimeLimit time.Duration = time.Hour * 24 * 30 +var activeUserTimeLimit = time.Hour * 24 * 30 func GetDataSourceStats(query *m.GetDataSourceStatsQuery) error { var rawSql = `SELECT COUNT(*) as count, type FROM data_source GROUP BY type` diff --git a/pkg/services/sqlstore/user.go b/pkg/services/sqlstore/user.go index 5e2efbd7fde..f19019d28a4 100644 --- a/pkg/services/sqlstore/user.go +++ b/pkg/services/sqlstore/user.go @@ -47,10 +47,9 @@ func getOrgIdForNewUser(cmd *m.CreateUserCommand, sess *DBSession) (int64, error } if has { return org.Id, nil - } else { - org.Name = "Main Org." - org.Id = 1 } + org.Name = "Main Org." + org.Id = 1 } else { org.Name = cmd.OrgName if len(org.Name) == 0 { diff --git a/pkg/setting/setting.go b/pkg/setting/setting.go index 3aeb9eddaf0..922eea607d1 100644 --- a/pkg/setting/setting.go +++ b/pkg/setting/setting.go @@ -39,7 +39,7 @@ const ( var ( // App settings. - Env string = DEV + Env = DEV AppUrl string AppSubUrl string InstanceName string @@ -158,7 +158,7 @@ var ( // LDAP LdapEnabled bool LdapConfigFile string - LdapAllowSignup bool = true + LdapAllowSignup = true // SMTP email settings Smtp SmtpSettings @@ -470,7 +470,7 @@ func setHomePath(args *CommandLineArgs) { } } -var skipStaticRootValidation bool = false +var skipStaticRootValidation = false func validateStaticRootPath() error { if skipStaticRootValidation { diff --git a/pkg/tsdb/cloudwatch/credentials.go b/pkg/tsdb/cloudwatch/credentials.go index 06848323fbb..8b32c76daa3 100644 --- a/pkg/tsdb/cloudwatch/credentials.go +++ b/pkg/tsdb/cloudwatch/credentials.go @@ -23,7 +23,7 @@ type cache struct { expiration *time.Time } -var awsCredentialCache map[string]cache = make(map[string]cache) +var awsCredentialCache = make(map[string]cache) var credentialCacheLock sync.RWMutex func GetCredentials(dsInfo *DatasourceInfo) (*credentials.Credentials, error) { diff --git a/pkg/tsdb/cloudwatch/metric_find_query.go b/pkg/tsdb/cloudwatch/metric_find_query.go index d73516ca88f..a7d33645b9b 100644 --- a/pkg/tsdb/cloudwatch/metric_find_query.go +++ b/pkg/tsdb/cloudwatch/metric_find_query.go @@ -222,9 +222,8 @@ func parseMultiSelectValue(input string) []string { trimValues[i] = strings.TrimSpace(v) } return trimValues - } else { - return []string{trimmedInput} } + return []string{trimmedInput} } // Whenever this list is updated, frontend list should also be updated. diff --git a/pkg/tsdb/influxdb/query.go b/pkg/tsdb/influxdb/query.go index 9fbe133c055..0637a5bbb44 100644 --- a/pkg/tsdb/influxdb/query.go +++ b/pkg/tsdb/influxdb/query.go @@ -12,8 +12,8 @@ import ( ) var ( - regexpOperatorPattern *regexp.Regexp = regexp.MustCompile(`^\/.*\/$`) - regexpMeasurementPattern *regexp.Regexp = regexp.MustCompile(`^\/.*\/$`) + regexpOperatorPattern = regexp.MustCompile(`^\/.*\/$`) + regexpMeasurementPattern = regexp.MustCompile(`^\/.*\/$`) ) func (query *Query) Build(queryContext *tsdb.TsdbQuery) (string, error) { diff --git a/pkg/tsdb/interval.go b/pkg/tsdb/interval.go index e26d39f3986..49904f27a37 100644 --- a/pkg/tsdb/interval.go +++ b/pkg/tsdb/interval.go @@ -10,10 +10,10 @@ import ( ) var ( - defaultRes int64 = 1500 - defaultMinInterval time.Duration = 1 * time.Millisecond - year time.Duration = time.Hour * 24 * 365 - day time.Duration = time.Hour * 24 + defaultRes int64 = 1500 + defaultMinInterval = time.Millisecond * 1 + year = time.Hour * 24 * 365 + day = time.Hour * 24 ) type Interval struct { diff --git a/pkg/tsdb/mssql/mssql_test.go b/pkg/tsdb/mssql/mssql_test.go index 167d02a1e07..e62d30a6325 100644 --- a/pkg/tsdb/mssql/mssql_test.go +++ b/pkg/tsdb/mssql/mssql_test.go @@ -22,7 +22,7 @@ import ( // There is also a dashboard.json in same directory that you can import to Grafana // once you've created a datasource for the test server/database. // If needed, change the variable below to the IP address of the database. -var serverIP string = "localhost" +var serverIP = "localhost" func TestMSSQL(t *testing.T) { SkipConvey("MSSQL", t, func() { diff --git a/pkg/tsdb/time_range.go b/pkg/tsdb/time_range.go index 777fd15907e..18e389e5993 100644 --- a/pkg/tsdb/time_range.go +++ b/pkg/tsdb/time_range.go @@ -54,19 +54,19 @@ func (tr *TimeRange) GetToAsTimeUTC() time.Time { } func (tr *TimeRange) MustGetFrom() time.Time { - if res, err := tr.ParseFrom(); err != nil { + res, err := tr.ParseFrom() + if err != nil { return time.Unix(0, 0) - } else { - return res } + return res } func (tr *TimeRange) MustGetTo() time.Time { - if res, err := tr.ParseTo(); err != nil { + res, err := tr.ParseTo() + if err != nil { return time.Unix(0, 0) - } else { - return res } + return res } func tryParseUnixMsEpoch(val string) (time.Time, bool) { diff --git a/pkg/util/filepath.go b/pkg/util/filepath.go index 3ad8cac3147..d304236fcb1 100644 --- a/pkg/util/filepath.go +++ b/pkg/util/filepath.go @@ -65,9 +65,8 @@ func walk(path string, info os.FileInfo, resolvedPath string, symlinkPathsFollow if _, ok := symlinkPathsFollowed[path2]; ok { errMsg := "Potential SymLink Infinite Loop. Path: %v, Link To: %v" return fmt.Errorf(errMsg, resolvedPath, path2) - } else { - symlinkPathsFollowed[path2] = true } + symlinkPathsFollowed[path2] = true } info2, err := os.Lstat(path2) if err != nil {