Skip to content

staticcheck failes: define your own type to avoid collisions (SA1029) #1200

Description

@tempcke

when security is defined in the openapi yaml like the following

paths:
  /foo:
    get:
      # ...
      security:
        - key: []
          secret: []
components:
  securitySchemes:
    key:
      type: apiKey
      in: header
      name: X-API-Key
    secret:
      type: apiKey
      in: header
      name: X-API-Secret

Then in the generated code it creates constants which it uses as context value keys like so

const (
	KeyScopes    = "key.Scopes"
	SecretScopes = "secret.Scopes"
)

func (siw *ServerInterfaceWrapper) GetFoo(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	ctx = context.WithValue(ctx, KeyScopes, []string{})

	ctx = context.WithValue(ctx, SecretScopes, []string{})

	handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		siw.Handler.GetFoo(w, r)
	}))

	for _, middleware := range siw.HandlerMiddlewares {
		handler = middleware(handler)
	}

	handler.ServeHTTP(w, r.WithContext(ctx))
}

which fails staticcheck

$ staticcheck ./...
api.gen.go:117:31:  should not use built-in type string as key for value; define your own type to avoid collisions (SA1029)

solution is to simply have the constants use a custom unexported type like this

type ctxKey string

const (
	KeyScopes    ctxKey = "key.Scopes"
	SecretScopes ctxKey = "secret.Scopes"
)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions