From 26ce90bb849565d307f8605855726fa0250e99be Mon Sep 17 00:00:00 2001 From: "Stanislav N. aka pztrn" Date: Sun, 21 Nov 2021 14:45:09 +0500 Subject: [PATCH] Linting fixes. --- .golangci.yml | 4 +-- cmd/metricator-client/main.go | 11 +++++--- cmd/metricatord/main.go | 3 +- internal/application/application.go | 8 ++++-- internal/application/config.go | 1 + internal/application/fetcher.go | 3 ++ internal/application/parser.go | 16 +++++------ internal/configuration/config.go | 6 ++-- internal/httpserver/handler.go | 44 ++++++++++++++--------------- internal/httpserver/httpserver.go | 7 +++-- internal/storage/memory/memory.go | 10 ++++--- pkg/client/client.go | 7 +++-- pkg/schema/metric.go | 4 +-- 13 files changed, 69 insertions(+), 55 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 5194d96..e16713a 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -12,8 +12,8 @@ linters: linters-settings: lll: line-length: 120 - gocyclo: - min-complexity: 40 + cyclop: + max-complexity: 40 gocognit: min-complexity: 40 funlen: diff --git a/cmd/metricator-client/main.go b/cmd/metricator-client/main.go index 8105061..f20e392 100644 --- a/cmd/metricator-client/main.go +++ b/cmd/metricator-client/main.go @@ -25,6 +25,9 @@ var ( output = flag.String("output", "json", "Output format. Can be 'json' or 'plain-by-line'.") ) +// This function uses fmt.Println to print lines without timestamps to make it easy +// to parse output, so: +// nolint:forbidigo func main() { config := configuration.NewConfig() @@ -83,17 +86,17 @@ func main() { Timeout: *metricatorTimeout, } - c := client.NewClient(clientConfig, logger) + clnt := client.NewClient(clientConfig, logger) var data interface{} switch { case *appsList: - data = c.GetAppsList() + data = clnt.GetAppsList() case *metricsList: - data = c.GetMetricsList(*application) + data = clnt.GetMetricsList(*application) case *metric != "": - data = c.GetMetric(*application, *metric) + data = clnt.GetMetric(*application, *metric) } switch *output { diff --git a/cmd/metricatord/main.go b/cmd/metricatord/main.go index 1a493ab..b33a05f 100644 --- a/cmd/metricatord/main.go +++ b/cmd/metricatord/main.go @@ -29,8 +29,7 @@ func main() { // Parse configuration. flag.Parse() - err := config.Parse() - if err != nil { + if err := config.Parse(); err != nil { log.Fatalln("Failed to parse configuration:", err.Error()) } diff --git a/internal/application/application.go b/internal/application/application.go index 297013d..572218d 100644 --- a/internal/application/application.go +++ b/internal/application/application.go @@ -28,16 +28,18 @@ type Application struct { // NewApplication creates new application. func NewApplication(ctx context.Context, name string, config *Config, logger *logger.Logger) *Application { - a := &Application{ + // Some variables are initialized in initialize() function. + // nolint:exhaustivestruct + app := &Application{ config: config, ctx: ctx, doneChan: make(chan struct{}), logger: logger, name: name, } - a.initialize() + app.initialize() - return a + return app } // GetDoneChan returns a channel which should be used to block execution until diff --git a/internal/application/config.go b/internal/application/config.go index 3843066..d2d3c60 100644 --- a/internal/application/config.go +++ b/internal/application/config.go @@ -11,5 +11,6 @@ type Config struct { Endpoint string `yaml:"endpoint"` // TimeBetweenRequests is a minimal amount of time which should pass // between requests. + // nolint:tagliatelle TimeBetweenRequests time.Duration `yaml:"time_between_requests"` } diff --git a/internal/application/fetcher.go b/internal/application/fetcher.go index 0a81013..95346e9 100644 --- a/internal/application/fetcher.go +++ b/internal/application/fetcher.go @@ -10,6 +10,9 @@ func (a *Application) fetch() { // Do not do anything if fetching is running. // ToDo: maybe another approach? a.fetchIsRunningMutex.RLock() + // This is an optimization to avoid excessive waiting when using Lock(). + // Most of time application will wait between fetches. + // nolint:ifshort isFetching := a.fetchIsRunning a.fetchIsRunningMutex.RUnlock() diff --git a/internal/application/parser.go b/internal/application/parser.go index 4a615f2..c569c7d 100644 --- a/internal/application/parser.go +++ b/internal/application/parser.go @@ -143,8 +143,8 @@ func (a *Application) getParametersForPrometheusMetric(line string) []string { paramNameFinished, paramValueStarted, paramValueFinished bool ) - for _, r := range valuesString { - if paramValueFinished && string(r) == "," { + for _, runeChar := range valuesString { + if paramValueFinished && string(runeChar) == "," { params = append(params, paramName+":"+paramValue) paramName, paramValue = "", "" paramNameFinished, paramValueStarted, paramValueFinished = false, false, false @@ -156,8 +156,8 @@ func (a *Application) getParametersForPrometheusMetric(line string) []string { // "deeply nested"? I think not. So: // nolint:nestif if !paramNameFinished { - if string(r) != "=" { - paramName += string(r) + if string(runeChar) != "=" { + paramName += string(runeChar) continue } else { @@ -166,19 +166,19 @@ func (a *Application) getParametersForPrometheusMetric(line string) []string { continue } } else { - if string(r) == "\"" && !paramValueStarted { + if string(runeChar) == "\"" && !paramValueStarted { paramValueStarted = true continue } - if paramValueStarted && string(r) != "\"" { - paramValue += string(r) + if paramValueStarted && string(runeChar) != "\"" { + paramValue += string(runeChar) continue } - if paramValueStarted && string(r) == "\"" { + if paramValueStarted && string(runeChar) == "\"" { paramValueFinished = true continue diff --git a/internal/configuration/config.go b/internal/configuration/config.go index 0c25e47..d87fbb6 100644 --- a/internal/configuration/config.go +++ b/internal/configuration/config.go @@ -21,16 +21,18 @@ var ( // Config is an application's configuration. type Config struct { - configPath string // Applications describes configuration for remote application's endpoints. // Key is an application's name. Applications map[string]*application.Config `yaml:"applications"` // Logger is a logging configuration. - Logger *logger.Config `yaml:"logger"` + Logger *logger.Config `yaml:"logger"` + configPath string } // NewConfig returns new configuration. func NewConfig() *Config { + // Fields are initialized when parsing YAML file. + // nolint:exhaustivestruct c := &Config{} c.initialize() diff --git a/internal/httpserver/handler.go b/internal/httpserver/handler.go index 8124d82..e4b9a34 100644 --- a/internal/httpserver/handler.go +++ b/internal/httpserver/handler.go @@ -48,14 +48,14 @@ func (h *handler) getAppsList() ([]byte, error) { // Gets request information from URL. Returns a structure with filled request // info and error if it occurs. -func (h *handler) getRequestInfo(r *http.Request) (*models.RequestInfo, error) { +func (h *handler) getRequestInfo(req *http.Request) (*models.RequestInfo, error) { // Request isn't for API or isn't versioned. - if !strings.HasPrefix(r.URL.Path, "/api/v") { + if !strings.HasPrefix(req.URL.Path, "/api/v") { return nil, errInvalidPath } // Note: first element will always be empty! - pathSplitted := strings.Split(r.URL.Path, "/") + pathSplitted := strings.Split(req.URL.Path, "/") // Request is for API but not enough items in URL was passed. if len(pathSplitted) < 4 { @@ -119,20 +119,20 @@ func (h *handler) register(appName string, hndl common.HTTPHandlerFunc) { } // ServeHTTP handles every HTTP request. -func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { +func (h *handler) ServeHTTP(writer http.ResponseWriter, req *http.Request) { startTime := time.Now() defer func() { requestDuration := time.Since(startTime) - log.Printf("[HTTP Request] from %s to %s, duration %.4fs\n", r.RemoteAddr, r.URL.Path, requestDuration.Seconds()) + log.Printf("[HTTP Request] from %s to %s, duration %.4fs\n", req.RemoteAddr, req.URL.Path, requestDuration.Seconds()) }() // Validate request and extract needed info. - rInfo, err := h.getRequestInfo(r) + rInfo, err := h.getRequestInfo(req) if err != nil { - w.WriteHeader(http.StatusBadRequest) - _, _ = w.Write([]byte("400 bad request - " + err.Error())) + writer.WriteHeader(http.StatusBadRequest) + _, _ = writer.Write([]byte("400 bad request - " + err.Error())) return } @@ -144,14 +144,14 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { case "apps_list": appsList, err := h.getAppsList() if err != nil { - w.WriteHeader(http.StatusBadRequest) - _, _ = w.Write([]byte("400 bad request - " + err.Error())) + writer.WriteHeader(http.StatusBadRequest) + _, _ = writer.Write([]byte("400 bad request - " + err.Error())) return } - w.WriteHeader(http.StatusOK) - _, _ = w.Write(appsList) + writer.WriteHeader(http.StatusOK) + _, _ = writer.Write(appsList) return case "info": @@ -169,15 +169,15 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { infoBytes, _ := json.Marshal(infoData) - w.WriteHeader(http.StatusOK) - _, _ = w.Write(infoBytes) + writer.WriteHeader(http.StatusOK) + _, _ = writer.Write(infoBytes) return case "metrics": handler, found := h.handlers[rInfo.Application] if !found { - w.WriteHeader(http.StatusBadRequest) - _, _ = w.Write([]byte("400 bad request - " + errInvalidApplication.Error())) + writer.WriteHeader(http.StatusBadRequest) + _, _ = writer.Write([]byte("400 bad request - " + errInvalidApplication.Error())) return } @@ -185,16 +185,16 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Get data from handler. data := handler(rInfo) if data == "" { - w.WriteHeader(http.StatusBadRequest) - _, _ = w.Write([]byte("400 bad request - " + errNoData.Error())) + writer.WriteHeader(http.StatusBadRequest) + _, _ = writer.Write([]byte("400 bad request - " + errNoData.Error())) } - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(data)) + writer.WriteHeader(http.StatusOK) + _, _ = writer.Write([]byte(data)) return } - w.WriteHeader(http.StatusBadRequest) - _, _ = w.Write([]byte("400 bad request - " + errInvalidPath.Error())) + writer.WriteHeader(http.StatusBadRequest) + _, _ = writer.Write([]byte("400 bad request - " + errInvalidPath.Error())) } diff --git a/internal/httpserver/httpserver.go b/internal/httpserver/httpserver.go index a65319d..41ec24c 100644 --- a/internal/httpserver/httpserver.go +++ b/internal/httpserver/httpserver.go @@ -25,15 +25,16 @@ type HTTPServer struct { // NewHTTPServer creates HTTP server and executes preliminary initialization // (HTTP server structure initialized but it doesn't start). func NewHTTPServer(ctx context.Context, cfg *configuration.Config, logger *logger.Logger) (*HTTPServer, chan struct{}) { - h := &HTTPServer{ + // nolint:exhaustivestruct + httpServer := &HTTPServer{ config: cfg, ctx: ctx, doneChan: make(chan struct{}), logger: logger, } - h.initialize() + httpServer.initialize() - return h, h.doneChan + return httpServer, httpServer.doneChan } // Returns request's context based on main context of application. diff --git a/internal/storage/memory/memory.go b/internal/storage/memory/memory.go index b3aa6e4..ce16407 100644 --- a/internal/storage/memory/memory.go +++ b/internal/storage/memory/memory.go @@ -14,25 +14,27 @@ var ErrMetricNotFound = errors.New("metric not found") // Storage is an in-memory storage. type Storage struct { + dataMutex sync.RWMutex ctx context.Context doneChan chan struct{} logger *logger.Logger data map[string]schema.Metric name string - dataMutex sync.RWMutex } // NewStorage creates new in-memory storage to use. func NewStorage(ctx context.Context, name string, logger *logger.Logger) (*Storage, chan struct{}) { - s := &Storage{ + // nolint:exhaustivestruct + storage := &Storage{ ctx: ctx, doneChan: make(chan struct{}), logger: logger, name: name, + data: make(map[string]schema.Metric), } - s.initialize() + storage.initialize() - return s, s.doneChan + return storage, storage.doneChan } // Get returns data from storage by key. diff --git a/pkg/client/client.go b/pkg/client/client.go index c65f741..236bfa5 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -23,13 +23,14 @@ type Client struct { // NewClient creates new Metricator client. func NewClient(config *Config, logger *logger.Logger) *Client { - c := &Client{ + // nolint:exhaustivestruct + client := &Client{ config: config, logger: logger, } - c.initialize() + client.initialize() - return c + return client } // Executes request and parses it's contents. diff --git a/pkg/schema/metric.go b/pkg/schema/metric.go index f6fa3fd..0f0bdc2 100644 --- a/pkg/schema/metric.go +++ b/pkg/schema/metric.go @@ -18,7 +18,7 @@ type Metric struct { // NewMetric creates new structure for storing single metric data. func NewMetric(name, mType, description string, params []string) Metric { - m := Metric{ + metric := Metric{ BaseName: name, Name: name, Description: description, @@ -27,7 +27,7 @@ func NewMetric(name, mType, description string, params []string) Metric { Value: "", } - return m + return metric } // GetValue returns metric's value.