Skip to content

Commit 1a7c609

Browse files
authored
refactor: fix gocritic lint issues (#3113)
1 parent 4114515 commit 1a7c609

24 files changed

+48
-35
lines changed

.golangci.yml

+13
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,15 @@ run:
33
timeout: 5m
44

55
linters-settings:
6+
gocritic:
7+
enabled-checks:
8+
- emptyStringTest
9+
- equalFold
10+
- httpNoBody
11+
- nilValReturn
12+
- paramTypeCombine
13+
- preferFprint
14+
- yodaStyleExpr
615
errcheck:
716
exclude-functions:
817
- (io.Writer).Write
@@ -69,6 +78,10 @@ issues:
6978
linters:
7079
- dupl
7180
- errcheck
81+
# It's autogenerated code.
82+
- path: codegen/testserver/.*/resolver\.go
83+
linters:
84+
- gocritic
7285
# Disable revive.use-any for backwards compatibility
7386
- path: graphql/map.go
7487
text: "use-any: since GO 1.18 'interface{}' can be replaced by 'any'"

_examples/chat/resolvers.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ type Chatroom struct {
6262

6363
type mutationResolver struct{ *resolver }
6464

65-
func (r *mutationResolver) Post(ctx context.Context, text string, username string, roomName string) (*Message, error) {
65+
func (r *mutationResolver) Post(ctx context.Context, text, username, roomName string) (*Message, error) {
6666
room := r.getRoom(roomName)
6767

6868
message := &Message{

_examples/scalars/model/model.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ func (b Banned) MarshalGQL(w io.Writer) {
2525
func (b *Banned) UnmarshalGQL(v any) error {
2626
switch v := v.(type) {
2727
case string:
28-
*b = strings.ToLower(v) == "true"
28+
*b = Banned(strings.EqualFold(v, "true"))
2929
return nil
3030
case bool:
3131
*b = Banned(v)

client/client.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ var boundaryRegex = regexp.MustCompile(`multipart/form-data; ?boundary=.*`)
111111
func (p *Client) newRequest(query string, options ...Option) (*http.Request, error) {
112112
bd := &Request{
113113
Query: query,
114-
HTTP: httptest.NewRequest(http.MethodPost, "/", nil),
114+
HTTP: httptest.NewRequest(http.MethodPost, "/", http.NoBody),
115115
}
116116
bd.HTTP.Header.Set("Content-Type", "application/json")
117117

@@ -128,7 +128,7 @@ func (p *Client) newRequest(query string, options ...Option) (*http.Request, err
128128
switch {
129129
case boundaryRegex.MatchString(contentType):
130130
break
131-
case "application/json" == contentType:
131+
case contentType == "application/json":
132132
requestBody, err := json.Marshal(bd)
133133
if err != nil {
134134
return nil, fmt.Errorf("encode: %w", err)
@@ -146,7 +146,7 @@ func (p *Client) SetCustomDecodeConfig(dc *mapstructure.DecoderConfig) {
146146
p.dc = dc
147147
}
148148

149-
func unpack(data any, into any, customDc *mapstructure.DecoderConfig) error {
149+
func unpack(data, into any, customDc *mapstructure.DecoderConfig) error {
150150
dc := &mapstructure.DecoderConfig{
151151
TagName: "json",
152152
ErrorUnused: true,

client/client_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ func TestSetCustomDecodeConfig(t *testing.T) {
182182
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
183183
w.WriteHeader(http.StatusOK)
184184
w.Header().Set("Content-Type", "application/json")
185-
w.Write([]byte(fmt.Sprintf(`{"data": {"created_at":"%s"}}`, now.Format(time.RFC3339))))
185+
fmt.Fprintf(w, `{"data": {"created_at":"%s"}}`, now.Format(time.RFC3339))
186186
})
187187

188188
dc := &mapstructure.DecoderConfig{

client/options.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ func Path(url string) Option {
3636
}
3737

3838
// AddHeader adds a header to the outgoing request. This is useful for setting expected Authentication headers for example.
39-
func AddHeader(key string, value string) Option {
39+
func AddHeader(key, value string) Option {
4040
return func(bd *Request) {
4141
bd.HTTP.Header.Add(key, value)
4242
}

codegen/config/binder.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ func (b *Binder) FindTypeFromName(name string) (types.Type, error) {
6161
return b.FindType(pkgName, typeName)
6262
}
6363

64-
func (b *Binder) FindType(pkgName string, typeName string) (types.Type, error) {
64+
func (b *Binder) FindType(pkgName, typeName string) (types.Type, error) {
6565
if pkgName == "" {
6666
if typeName == "map[string]interface{}" {
6767
return MapType, nil
@@ -123,7 +123,7 @@ func (b *Binder) DefaultUserObject(name string) (types.Type, error) {
123123
return obj.Type(), nil
124124
}
125125

126-
func (b *Binder) FindObject(pkgName string, typeName string) (types.Object, error) {
126+
func (b *Binder) FindObject(pkgName, typeName string) (types.Object, error) {
127127
if pkgName == "" {
128128
return nil, errors.New("package cannot be nil")
129129
}
@@ -349,7 +349,7 @@ func isIntf(t types.Type) bool {
349349

350350
func unwrapOmittable(t types.Type) (types.Type, bool) {
351351
if t == nil {
352-
return t, false
352+
return nil, false
353353
}
354354
named, ok := t.(*types.Named)
355355
if !ok {

codegen/config/config.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -644,7 +644,7 @@ func (tm TypeMap) ReferencedPackages() []string {
644644
return pkgs
645645
}
646646

647-
func (tm TypeMap) Add(name string, goType string) {
647+
func (tm TypeMap) Add(name, goType string) {
648648
modelCfg := tm[name]
649649
modelCfg.Model = append(modelCfg.Model, goType)
650650
tm[name] = modelCfg

codegen/templates/templates.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@ func parseTemplates(cfg Options, t *template.Template) (*template.Template, erro
185185
return t, nil
186186
}
187187

188-
func center(width int, pad string, s string) string {
188+
func center(width int, pad, s string) string {
189189
if len(s)+2 > width {
190190
return s
191191
}

graphql/bool.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ func MarshalBoolean(b bool) Marshaler {
1515
func UnmarshalBoolean(v any) (bool, error) {
1616
switch v := v.(type) {
1717
case string:
18-
return strings.ToLower(v) == "true", nil
18+
return strings.EqualFold(v, "true"), nil
1919
case int:
2020
return v != 0, nil
2121
case bool:

graphql/context_field.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ func WithFieldContext(ctx context.Context, rc *FieldContext) context.Context {
9898
return context.WithValue(ctx, resolverCtx, rc)
9999
}
100100

101-
func equalPath(a ast.Path, b ast.Path) bool {
101+
func equalPath(a, b ast.Path) bool {
102102
if len(a) != len(b) {
103103
return false
104104
}

graphql/executable_schema.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ func instanceOf(val string, satisfies []string) bool {
116116
return false
117117
}
118118

119-
func getOrCreateAndAppendField(c *[]CollectedField, name string, alias string, objectDefinition *ast.Definition, creator func() CollectedField) *CollectedField {
119+
func getOrCreateAndAppendField(c *[]CollectedField, name, alias string, objectDefinition *ast.Definition, creator func() CollectedField) *CollectedField {
120120
for i, cf := range *c {
121121
if cf.Name == name && cf.Alias == alias {
122122
if cf.ObjectDefinition == objectDefinition {

graphql/float.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import (
1212

1313
func MarshalFloat(f float64) Marshaler {
1414
return WriterFunc(func(w io.Writer) {
15-
io.WriteString(w, fmt.Sprintf("%g", f))
15+
fmt.Fprintf(w, "%g", f)
1616
})
1717
}
1818

@@ -38,7 +38,7 @@ func MarshalFloatContext(f float64) ContextMarshaler {
3838
if math.IsInf(f, 0) || math.IsNaN(f) {
3939
return errors.New("cannot marshal infinite no NaN float values")
4040
}
41-
io.WriteString(w, fmt.Sprintf("%g", f))
41+
fmt.Fprintf(w, "%g", f)
4242
return nil
4343
})
4444
}

graphql/handler/extension/complexity_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ func TestFixedComplexity(t *testing.T) {
108108
})
109109
}
110110

111-
func doRequest(handler http.Handler, method string, target string, body string) *httptest.ResponseRecorder {
111+
func doRequest(handler http.Handler, method, target, body string) *httptest.ResponseRecorder {
112112
r := httptest.NewRequest(method, target, strings.NewReader(body))
113113
r.Header.Set("Content-Type", "application/json")
114114
w := httptest.NewRecorder()

graphql/handler/server_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -186,15 +186,15 @@ func TestRecover(t *testing.T) {
186186
}
187187

188188
func get(handler http.Handler, target string) *httptest.ResponseRecorder {
189-
r := httptest.NewRequest("GET", target, nil)
189+
r := httptest.NewRequest("GET", target, http.NoBody)
190190
w := httptest.NewRecorder()
191191

192192
handler.ServeHTTP(w, r)
193193
return w
194194
}
195195

196196
func post(handler http.Handler, target, contentType string) *httptest.ResponseRecorder {
197-
r := httptest.NewRequest("POST", target, nil)
197+
r := httptest.NewRequest("POST", target, http.NoBody)
198198
r.Header.Set("Content-Type", contentType)
199199
w := httptest.NewRecorder()
200200

graphql/handler/transport/http_graphql_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ func TestGRAPHQL(t *testing.T) {
9797
})
9898
}
9999

100-
func doGraphqlRequest(handler http.Handler, method string, target string, body string) *httptest.ResponseRecorder {
100+
func doGraphqlRequest(handler http.Handler, method, target, body string) *httptest.ResponseRecorder {
101101
r := httptest.NewRequest(method, target, strings.NewReader(body))
102102
r.Header.Set("Content-Type", "application/graphql")
103103
w := httptest.NewRecorder()

graphql/handler/transport/http_post_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ func TestPOST(t *testing.T) {
9898
})
9999
}
100100

101-
func doRequest(handler http.Handler, method string, target string, body string, contentType string) *httptest.ResponseRecorder {
101+
func doRequest(handler http.Handler, method, target, body, contentType string) *httptest.ResponseRecorder {
102102
r := httptest.NewRequest(method, target, strings.NewReader(body))
103103
r.Header.Set("Content-Type", contentType)
104104
w := httptest.NewRecorder()

graphql/playground/helper_test.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import (
1616

1717
func testResourceIntegrity(t *testing.T, handler func(title, endpoint string) http.HandlerFunc) {
1818
recorder := httptest.NewRecorder()
19-
request := httptest.NewRequest(http.MethodGet, "http://localhost:8080/", nil)
19+
request := httptest.NewRequest(http.MethodGet, "http://localhost:8080/", http.NoBody)
2020
handler("example.org API", "/query").ServeHTTP(recorder, request)
2121

2222
res := recorder.Result()
@@ -40,7 +40,7 @@ func testResourceIntegrity(t *testing.T, handler func(title, endpoint string) ht
4040
assertNodesIntegrity(t, baseUrl, doc, "link", "href", "integrity")
4141
}
4242

43-
func assertNodesIntegrity(t *testing.T, baseUrl string, doc *goquery.Document, selector string, urlAttrKey, integrityAttrKey string) {
43+
func assertNodesIntegrity(t *testing.T, baseUrl string, doc *goquery.Document, selector, urlAttrKey, integrityAttrKey string) {
4444
selection := doc.Find(selector)
4545
for _, node := range selection.Nodes {
4646
var url string
@@ -53,11 +53,11 @@ func assertNodesIntegrity(t *testing.T, baseUrl string, doc *goquery.Document, s
5353
}
5454
}
5555

56-
if len(integrity) != 0 {
56+
if integrity != "" {
5757
assert.NotEmpty(t, url)
5858
}
5959

60-
if len(url) != 0 && len(integrity) != 0 {
60+
if url != "" && integrity != "" {
6161
resp, err := http.Get(baseUrl + url)
6262
require.NoError(t, err)
6363
hasher := sha256.New()

graphql/playground/playground.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -85,14 +85,14 @@ var page = template.Must(template.New("graphiql").Parse(`<!DOCTYPE html>
8585
`))
8686

8787
// Handler responsible for setting up the playground
88-
func Handler(title string, endpoint string) http.HandlerFunc {
88+
func Handler(title, endpoint string) http.HandlerFunc {
8989
return HandlerWithHeaders(title, endpoint, nil, nil)
9090
}
9191

9292
// HandlerWithHeaders sets up the playground.
9393
// fetcherHeaders are used by the playground's fetcher instance and will not be visible in the UI.
9494
// uiHeaders are default headers that will show up in the UI headers editor.
95-
func HandlerWithHeaders(title string, endpoint string, fetcherHeaders map[string]string, uiHeaders map[string]string) http.HandlerFunc {
95+
func HandlerWithHeaders(title, endpoint string, fetcherHeaders, uiHeaders map[string]string) http.HandlerFunc {
9696
return func(w http.ResponseWriter, r *http.Request) {
9797
w.Header().Add("Content-Type", "text/html; charset=UTF-8")
9898
err := page.Execute(w, map[string]any{

graphql/playground/playground_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import (
1010

1111
func TestHandler_createsAbsoluteURLs(t *testing.T) {
1212
rec := httptest.NewRecorder()
13-
req := httptest.NewRequest(http.MethodGet, "https://example.org/query", nil)
13+
req := httptest.NewRequest(http.MethodGet, "https://example.org/query", http.NoBody)
1414
h := Handler("example.org API", "https://example.org/query")
1515
h.ServeHTTP(rec, req)
1616

@@ -43,7 +43,7 @@ func TestHandler_createsAbsoluteURLs(t *testing.T) {
4343

4444
func TestHandler_createsRelativeURLs(t *testing.T) {
4545
rec := httptest.NewRecorder()
46-
req := httptest.NewRequest(http.MethodGet, "http://localhost:8080/query", nil)
46+
req := httptest.NewRequest(http.MethodGet, "http://localhost:8080/query", http.NoBody)
4747
h := Handler("example.org API", "/customquery")
4848
h.ServeHTTP(rec, req)
4949

handler/handler.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -244,12 +244,12 @@ func (a apqAdapter) Add(ctx context.Context, key string, value any) {
244244
}
245245

246246
type PersistedQueryCache interface {
247-
Add(ctx context.Context, hash string, query string)
247+
Add(ctx context.Context, hash, query string)
248248
Get(ctx context.Context, hash string) (string, bool)
249249
}
250250

251251
// Deprecated: use playground.Handler instead
252-
func Playground(title string, endpoint string) http.HandlerFunc {
252+
func Playground(title, endpoint string) http.HandlerFunc {
253253
return playground.Handler(title, endpoint)
254254
}
255255

plugin/modelgen/models.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -622,7 +622,7 @@ func removeDuplicateTags(t string) string {
622622
key := kv[0]
623623
value := strings.Join(kv[1:], ":")
624624
processed[key] = true
625-
if len(returnTags) > 0 {
625+
if returnTags != "" {
626626
returnTags = " " + returnTags
627627
}
628628

plugin/resolvergen/resolver.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ func (r *Resolver) Implementation() string {
269269
return r.ImplementationStr
270270
}
271271

272-
func gqlToResolverName(base string, gqlname, filenameTmpl string) string {
272+
func gqlToResolverName(base, gqlname, filenameTmpl string) string {
273273
gqlname = filepath.Base(gqlname)
274274
ext := filepath.Ext(gqlname)
275275
if filenameTmpl == "" {

plugin/stubgen/stubs.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import (
1515
//go:embed stubs.gotpl
1616
var stubsTemplate string
1717

18-
func New(filename string, typename string) plugin.Plugin {
18+
func New(filename, typename string) plugin.Plugin {
1919
return &Plugin{filename: filename, typeName: typename}
2020
}
2121

0 commit comments

Comments
 (0)