Skip to content

Commit

Permalink
CLEANUP/MAJOR: lint: upgrade linter for go 1.22
Browse files Browse the repository at this point in the history
  • Loading branch information
mjuraga committed Apr 5, 2024
1 parent f912aa3 commit 8e1b865
Show file tree
Hide file tree
Showing 25 changed files with 56 additions and 71 deletions.
15 changes: 6 additions & 9 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ linters-settings:
min-occurrences: 2
revive:
rules:
- name: var-naming
severity: warning
disabled: true
- name: var-naming
severity: warning
disabled: true
linters:
enable-all: true
disable:
Expand Down Expand Up @@ -74,13 +74,12 @@ linters:
- tagalign
- depguard


issues:
exclude:
# bugs of typecheck linter
- "undeclared name: `shellquote`"
- "github.com/kballard/go-shellquote\" imported but not used"
- "github.com/haproxytech/config-parser/v5/types\" imported but not used"
- 'github.com/kballard/go-shellquote" imported but not used'
- 'github.com/haproxytech/config-parser/v5/types" imported but not used'
exclude-rules:
- linters:
- staticcheck
Expand All @@ -91,7 +90,5 @@ issues:
- linters:
- gosec
text: "G[404]"

run:
skip-dirs:
exclude-dirs:
- test
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ GIT_MODIFIED=${GIT_MODIFIED1}${GIT_MODIFIED2}
SWAGGER_VERSION=${shell curl -s https://raw.githubusercontent.com/haproxytech/client-native/master/Makefile | grep SWAGGER_VERSION -m 1 | awk -F"=" '{print $$2}'}
BUILD_DATE=$(shell date -u '+%Y-%m-%dT%H:%M:%SZ')
CGO_ENABLED?=0
GOLANGCI_LINT_VERSION=1.54.2
GOLANGCI_LINT_VERSION=1.57.1

all: update clean build

Expand Down
3 changes: 2 additions & 1 deletion configuration/cluster_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
"errors"
"fmt"
"io"
"net/http"
Expand Down Expand Up @@ -148,7 +149,7 @@ func (c *ClusterSync) issueRefreshRequest(url, port, basePath string, nodesPath

req, err := http.NewRequest(http.MethodPatch, url, bytes.NewBuffer(bytesRepresentation))
if err != nil {
return fmt.Errorf("error creating new POST request for cluster comunication")
return errors.New("error creating new POST request for cluster comunication")
}
req.Header.Add("X-Node-Key", c.cfg.Cluster.Token.Load())
req.Header.Add("Content-Type", "application/json")
Expand Down
4 changes: 2 additions & 2 deletions configuration/map_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func (ms *MapSync) Sync(mp *models.Map, client client_native.HAProxyClient) (boo
sort.Slice(fileEntries, func(i, j int) bool { return fileEntries[i].Key < fileEntries[j].Key })

// runtime map entries
id := fmt.Sprintf("#%s", mp.ID)
id := "#" + mp.ID
runtimeEntries, err := runtime.ShowMapEntries(id)
if err != nil {
return false, fmt.Errorf("getting runtime entries error: id: %s %s", id, err.Error())
Expand Down Expand Up @@ -144,7 +144,7 @@ func equalSomeEntries(fEntries, rEntries models.MapEntries, index ...int) bool {
maxRandom = max
}

for i := 0; i < maxRandom; i++ {
for range maxRandom {
// There's no need for strong number generation, here, just need for performance
r := rand.Intn(max)
if len(index) > 0 {
Expand Down
2 changes: 1 addition & 1 deletion configuration/map_sync_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
)

func data(differentAtIndex ...int) (fileEntries models.MapEntries, runtimeEntries models.MapEntries) {
for i := 0; i < 50; i++ {
for i := range 50 {
fe := &models.MapEntry{Key: "k" + strconv.Itoa(i), Value: "v" + strconv.Itoa(i)}
re := &models.MapEntry{Key: "k" + strconv.Itoa(i), Value: "v" + strconv.Itoa(i)}
fileEntries = append(fileEntries, fe)
Expand Down
3 changes: 1 addition & 2 deletions configuration/pid.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
package configuration

import (
"fmt"
"os"
"strconv"

Expand Down Expand Up @@ -47,7 +46,7 @@ func HandlePIDFile(haproxyOptions HAProxyConfiguration) {
}
}

err := renameio.WriteFile(haproxyOptions.PIDFile, []byte(fmt.Sprintf("%d", os.Getpid())), 0o644)
err := renameio.WriteFile(haproxyOptions.PIDFile, []byte(strconv.Itoa(os.Getpid())), 0o644)
if err != nil {
log.Fatalf("error while writing PID file: %s %s", haproxyOptions.PIDFile, err.Error())
} else {
Expand Down
7 changes: 5 additions & 2 deletions configuration/reload-strategy.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@

package configuration

import "fmt"
import (
"errors"
"fmt"
)

const (
ReloadStratCustom = "custom"
Expand Down Expand Up @@ -53,7 +56,7 @@ func validateReloadConfiguration(c *HAProxyConfiguration) error {
case ReloadStratCustom:
// The custom commands need to be set.
if c.ReloadCmd == "" || c.RestartCmd == "" {
return fmt.Errorf("the custom reload strategy requires these options to be set: " +
return errors.New("the custom reload strategy requires these options to be set: " +
"ReloadCmd, RestartCmd")
}
case ReloadStratS6:
Expand Down
4 changes: 2 additions & 2 deletions configuration/watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ package configuration
import (
"context"
"crypto/md5"
"fmt"
"encoding/hex"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -108,6 +108,6 @@ func (w *ConfigWatcher) invalidHash() bool {
return true
}
bHash := md5.Sum([]byte(strings.Join(lines[1:], "\n")))
hash := fmt.Sprintf("%x", bHash)
hash := hex.EncodeToString(bHash[:])
return parts[1] != hash
}
1 change: 1 addition & 0 deletions configure_data_plane.go
Original file line number Diff line number Diff line change
Expand Up @@ -1032,6 +1032,7 @@ func handleSignals(ctx context.Context, cancel context.CancelFunc, sigs chan os.
reloadConfigurationFile(client, haproxyOptions, users)
}
case <-ctx.Done():
cancel()
return
}
}
Expand Down
5 changes: 2 additions & 3 deletions discovery/aws_service_discovery_instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,9 @@ func newAWSRegionInstance(ctx context.Context, params *models.AwsRegion, client
func (a *awsInstance) filterConverter(in []*models.AwsFilters) (out []types.Filter) {
out = make([]types.Filter, len(in))
for i, l := range in {
filter := l
out[i] = types.Filter{
Name: filter.Key,
Values: []string{aws.ToString(filter.Value)},
Name: l.Key,
Values: []string{aws.ToString(l.Value)},
}
}
return
Expand Down
5 changes: 3 additions & 2 deletions discovery/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package discovery

import (
"errors"
"fmt"
"sync"
)
Expand Down Expand Up @@ -72,7 +73,7 @@ func (s *instanceStore) Create(name string, service interface{}) error {
defer s.mu.Unlock()

if _, err := s.get(name); err == nil {
return fmt.Errorf("instance already exists")
return errors.New("instance already exists")
}

s.store[name] = service
Expand Down Expand Up @@ -102,7 +103,7 @@ func (s *instanceStore) get(name string) (sd interface{}, err error) {
var ok bool
sd, ok = s.store[name]
if !ok {
return nil, fmt.Errorf("instance not found")
return nil, errors.New("instance not found")
}
return
}
4 changes: 2 additions & 2 deletions generate/go-generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ func getExample(att Attribute) string {
if att.Example != "" {
if att.Type == "int" {
i, _ := strconv.ParseInt(att.Example, 10, 64)
return fmt.Sprintf("%d", i)
return strconv.FormatInt(i, 10)
}
return att.Example
}
Expand All @@ -250,7 +250,7 @@ func getExample(att Attribute) string {
if v, ok := itemDefaults[att.FileName]; ok {
switch t := v.(type) {
case int:
return fmt.Sprintf("%d", v.(int))
return strconv.Itoa(v.(int))
default:
return t.(string)
}
Expand Down
6 changes: 3 additions & 3 deletions handlers/bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
package handlers

import (
"fmt"
"errors"

"github.com/go-openapi/runtime/middleware"
client_native "github.com/haproxytech/client-native/v4"
Expand Down Expand Up @@ -60,10 +60,10 @@ func bindTypeParams(frontend *string, parentType *string, parentName *string) (p
return "frontend", *frontend, nil
}
if parentType == nil || *parentType == "" {
return "", "", fmt.Errorf("parentType empty")
return "", "", errors.New("parentType empty")
}
if parentName == nil || *parentName == "" {
return "", "", fmt.Errorf("parentName empty")
return "", "", errors.New("parentName empty")
}
return *parentType, *parentName, nil
}
Expand Down
3 changes: 2 additions & 1 deletion handlers/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package handlers

import (
"errors"
"fmt"
"reflect"
"strings"
Expand Down Expand Up @@ -245,7 +246,7 @@ func (h *EditClusterHandlerImpl) Handle(params cluster.EditClusterParams, princi
}
return cluster.NewEditClusterOK().WithPayload(getClusterSettings(h.Config))
}
return h.err406(fmt.Errorf("dataplaneapi in single mode"))
return h.err406(errors.New("dataplaneapi in single mode"))
}

func (h *EditClusterHandlerImpl) err406(err error) middleware.Responder {
Expand Down
2 changes: 1 addition & 1 deletion handlers/frontend.go
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ func (h *ReplaceFrontendHandlerImpl) Handle(params frontend.ReplaceFrontendParam
return frontend.NewReplaceFrontendDefault(int(*e.Code)).WithPayload(e)
}
if params.TransactionID == nil {
reload := changeThroughRuntimeAPI(*params.Data, *ondisk, "", "", h.Client)
reload := changeThroughRuntimeAPI(*params.Data, *ondisk, "", h.Client)
if reload {
if *params.ForceReload {
err := h.ReloadAgent.ForceReload()
Expand Down
4 changes: 2 additions & 2 deletions handlers/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ var RuntimeSupportedFields = map[string][]string{

// ChangeThroughRuntimeAPI checks if something can be changed through the runtime API, and
// returns false if reload is not needed, or true if needed.
func changeThroughRuntimeAPI(data, ondisk interface{}, parentName, parentType string, client client_native.HAProxyClient) (reload bool) {
func changeThroughRuntimeAPI(data, ondisk interface{}, parentName string, client client_native.HAProxyClient) (reload bool) {
// reflect kinds and values are loosely checked as they are bound strictly in
// schema, but in case of any panic, we will log and reload to ensure
// changes go through
Expand Down Expand Up @@ -183,7 +183,7 @@ func compareObjects(data, ondisk interface{}) []string {
diff := make([]string, 0)
dataVal := reflect.ValueOf(data)
ondiskVal := reflect.ValueOf(ondisk)
for i := 0; i < dataVal.NumField(); i++ {
for i := range dataVal.NumField() {
fName := dataVal.Type().Field(i).Name
dataField := dataVal.FieldByName(fName)
ondiskField := ondiskVal.FieldByName(fName)
Expand Down
8 changes: 4 additions & 4 deletions handlers/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
package handlers

import (
"fmt"
"errors"

"github.com/haproxytech/client-native/v4/runtime"

Expand Down Expand Up @@ -63,10 +63,10 @@ func serverTypeParams(backend *string, parentType *string, parentName *string) (
return "backend", *backend, nil
}
if parentType == nil || *parentType == "" {
return "", "", fmt.Errorf("parentType empty")
return "", "", errors.New("parentType empty")
}
if parentName == nil || *parentName == "" {
return "", "", fmt.Errorf("parentName empty")
return "", "", errors.New("parentName empty")
}
return *parentType, *parentName, nil
}
Expand Down Expand Up @@ -314,7 +314,7 @@ func (h *ReplaceServerHandlerImpl) Handle(params server.ReplaceServerParams, pri
return server.NewReplaceServerDefault(int(*e.Code)).WithPayload(e)
}
if params.TransactionID == nil {
reload := changeThroughRuntimeAPI(*params.Data, *ondisk, pType, "", h.Client)
reload := changeThroughRuntimeAPI(*params.Data, *ondisk, pName, h.Client)
if reload {
if *params.ForceReload {
err := h.ReloadAgent.ForceReload()
Expand Down
2 changes: 1 addition & 1 deletion handlers/server_template.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ func (h *ReplaceServerTemplateHandlerImpl) Handle(params server_template.Replace
return server_template.NewReplaceServerTemplateDefault(int(*e.Code)).WithPayload(e)
}
if params.TransactionID == nil {
reload := changeThroughRuntimeAPI(*params.Data, *ondisk, params.Backend, "", h.Client)
reload := changeThroughRuntimeAPI(*params.Data, *ondisk, params.Backend, h.Client)
if reload {
if *params.ForceReload {
err := h.ReloadAgent.ForceReload()
Expand Down
9 changes: 5 additions & 4 deletions haproxy/reload_agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package haproxy
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
Expand All @@ -42,10 +43,10 @@ const (

type IReloadAgent interface {
Reload() string
ReloadWithCallback(func()) string
ReloadWithCallback(callback func()) string
Restart() error
ForceReload() error
ForceReloadWithCallback(func()) error
ForceReloadWithCallback(callback func()) error
Status() (bool, error)
GetReloads() models.Reloads
GetReload(id string) *models.Reload
Expand Down Expand Up @@ -479,7 +480,7 @@ func (ra *ReloadAgent) Status() (bool, error) {

func (ra *ReloadAgent) status() (bool, error) {
if ra.statusCmd == "" {
return false, fmt.Errorf("status command not configured")
return false, errors.New("status command not configured")
}
resp, err := execCmd(ra.statusCmd)
if err != nil {
Expand Down Expand Up @@ -511,7 +512,7 @@ type ReloadError struct {

// Error implementation for ConfError
func (e *ReloadError) Error() string {
return fmt.Sprintf(e.msg)
return e.msg
}

// NewReloadError constructor for ReloadError
Expand Down
7 changes: 4 additions & 3 deletions haproxy/reload_agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,17 @@ import (
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestReloadAgentDoesntMissReloads(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
f, err := os.CreateTemp("", "config.cfg")
assert.Nil(t, err)
require.NoError(t, err)
assert.NotNil(t, f)
t.Cleanup(func() {
cancel()
assert.Nil(t, os.Remove(f.Name()))
assert.NoError(t, os.Remove(f.Name()))
})

reloadAgentParams := ReloadAgentParams{
Expand All @@ -45,7 +46,7 @@ func TestReloadAgentDoesntMissReloads(t *testing.T) {
}

ra, err := NewReloadAgent(reloadAgentParams)
assert.Nil(t, err)
require.NoError(t, err)
assert.NotNil(t, ra)

var reloadID, firstReloadID, secondReloadID string
Expand Down
Loading

0 comments on commit 8e1b865

Please sign in to comment.