Skip to content

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

Closed

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

  1. changed the title [-]staticcheck [/-] [+]staticcheck failes: define your own type to avoid collisions (SA1029)[/+] on Aug 20, 2023
  2. added a commit that references this issue on Sep 21, 2023
    92fddcf
  3. asger-noer commented on Sep 21, 2023

    @asger-noer

    But @tempcke, if you want to fix this before a fix is made in oapi-codegen there is an option to do the following:

    Create a local templates/constants.tmpl:

    {{- if gt (len .SecuritySchemeProviderNames) 0 }}
    
    // contextKey provides a type for use with context.WithValue.
    type contextKey string
    
    const (
    {{range $ProviderName := .SecuritySchemeProviderNames}}
        {{- $ProviderName | sanitizeGoIdentity | ucFirst}}Scopes contextKey = "{{$ProviderName}}.Scopes"
    {{end}}
    )
    {{end}}
    {{range $Enum := .EnumDefinitions}}
    // Defines values for {{$Enum.TypeName}}.
    const (
    {{range $name, $value := $Enum.GetValues}}
      {{$name}} {{$Enum.TypeName}} = {{$Enum.ValueWrapper}}{{$value}}{{$Enum.ValueWrapper -}}
    {{end}}
    )
    {{end}}

    Then add this to your config file:

    # ...
    output-options:
      user-templates: 
        constants.tmpl: templates/constants.tmpl
    # ...
  4. added a commit that references this issue on Sep 21, 2023
    d549c37
  5. tboerger commented on May 13, 2024

    @tboerger
    Contributor

    The snippet from @asger-noer works like a charm, would be great to get this fix included.

  6. mromaszewicz commented on May 1, 2026

    @mromaszewicz
    Member

    PR #1187 (merged as commit a13ef41) added GenerateTypesForSecuritySchemes which creates a custom unexported type per security scheme (e.g. 'type keyContextKey string'). The constants template was updated to use that type for the scope constants, satisfying staticcheck SA1029. Multiple generated test files confirm the typed constants are produced correctly.

    Closing as fixed. If you can still reproduce on a recent release, please reopen with the exact spec and version used.

  7. tboerger commented on May 7, 2026

    @tboerger
    Contributor

    Great to see this improved on the project. I have personally also added for my own project something like the following to the constants.tmpl file to get some helper for converting strings to correct enums:

    var (
    	// Err{{$Enum.TypeName}} defines an error if an invalid value gets mapped.
    	Err{{$Enum.TypeName}} = fmt.Errorf("invalid type for {{$Enum.TypeName}}")
    
    	stringTo{{$Enum.TypeName}} = map[string]{{$Enum.TypeName}}{
    {{range $name, $value := $Enum.GetValues -}}
    		{{$Enum.ValueWrapper}}{{$value}}{{$Enum.ValueWrapper -}}: {{$name}},
    {{end -}}
    	}
    )
    
    // To{{$Enum.TypeName}} acts as a helper to map a string to the defined enum.
    func To{{$Enum.TypeName}}(val string) ({{$Enum.TypeName}}, error) {
    	if res, ok := stringTo{{$Enum.TypeName}}[val]; ok {
    		return res, nil
    	}
    
    	return {{$Enum.TypeName}}(""), Err{{$Enum.TypeName}}
    }
    
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