Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 24 additions & 20 deletions cmd/oapi-codegen/oapi-codegen.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,28 +35,30 @@ func errExit(format string, args ...interface{}) {
}

var (
flagPackageName string
flagGenerate string
flagOutputFile string
flagIncludeTags string
flagExcludeTags string
flagTemplatesDir string
flagImportMapping string
flagExcludeSchemas string
flagConfigFile string
flagAliasTypes bool
flagPrintVersion bool
flagPackageName string
flagGenerate string
flagOutputFile string
flagIncludeTags string
flagExcludeTags string
flagTemplatesDir string
flagImportMapping string
flagExcludeSchemas string
flagConfigFile string
flagResponseTypeSuffix string
flagAliasTypes bool
flagPrintVersion bool
)

type configuration struct {
PackageName string `yaml:"package"`
GenerateTargets []string `yaml:"generate"`
OutputFile string `yaml:"output"`
IncludeTags []string `yaml:"include-tags"`
ExcludeTags []string `yaml:"exclude-tags"`
TemplatesDir string `yaml:"templates"`
ImportMapping map[string]string `yaml:"import-mapping"`
ExcludeSchemas []string `yaml:"exclude-schemas"`
PackageName string `yaml:"package"`
GenerateTargets []string `yaml:"generate"`
OutputFile string `yaml:"output"`
IncludeTags []string `yaml:"include-tags"`
ExcludeTags []string `yaml:"exclude-tags"`
TemplatesDir string `yaml:"templates"`
ImportMapping map[string]string `yaml:"import-mapping"`
ExcludeSchemas []string `yaml:"exclude-schemas"`
ResponseTypeSuffix string `yaml:"response-type-suffix"`
}

func main() {
Expand All @@ -71,6 +73,7 @@ func main() {
flag.StringVar(&flagImportMapping, "import-mapping", "", "A dict from the external reference to golang package path")
flag.StringVar(&flagExcludeSchemas, "exclude-schemas", "", "A comma separated list of schemas which must be excluded from generation")
flag.StringVar(&flagConfigFile, "config", "", "a YAML config file that controls oapi-codegen behavior")
flag.StringVar(&flagResponseTypeSuffix, "response-type-suffix", "", "the suffix used for responses types")
flag.BoolVar(&flagAliasTypes, "alias-types", false, "Alias type declarations of possible")
flag.BoolVar(&flagPrintVersion, "version", false, "when specified, print version and exit")
flag.Parse()
Expand Down Expand Up @@ -104,7 +107,8 @@ func main() {
}

opts := codegen.Options{
AliasTypes: flagAliasTypes,
AliasTypes: flagAliasTypes,
ResponseTypeSuffix: flagResponseTypeSuffix,
}
for _, g := range cfg.GenerateTargets {
switch g {
Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.0-20210816181553-5444fa50b93d h1:
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.0-20210816181553-5444fa50b93d/go.mod h1:tmAIfUFEirG/Y8jhZ9M+h36obRZAk/1fcSpXwAVlfqE=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/getkin/kin-openapi v0.61.0 h1:6awGqF5nG5zkVpMsAih1QH4VgzS8phTxECUWIFo7zko=
github.com/getkin/kin-openapi v0.61.0/go.mod h1:7Yn5whZr5kJi6t+kShccXS8ae1APpYTW6yheSwk8Yi4=
github.com/getkin/kin-openapi v0.80.0 h1:W/s5/DNnDCR8P+pYyafEWlGk4S7/AfQUWXgrRSSAzf8=
github.com/getkin/kin-openapi v0.80.0/go.mod h1:660oXbgy5JFMKreazJaQTw7o+X00qeSyhcnluiMv+Xg=
github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk=
Expand Down
6 changes: 6 additions & 0 deletions pkg/codegen/codegen.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ type Options struct {
UserTemplates map[string]string // Override built-in templates from user-provided files
ImportMapping map[string]string // ImportMapping specifies the golang package path for each external reference
ExcludeSchemas []string // Exclude from generation schemas with given names. Ignored when empty.
ResponseTypeSuffix string // The suffix used for responses types
}

// goImport represents a go package to be imported in the generated code
Expand Down Expand Up @@ -111,6 +112,11 @@ func Generate(swagger *openapi3.T, packageName string, opts Options) (string, er
pruneUnusedComponents(swagger)
}

// if we are provided an override for the response type suffix update it
if opts.ResponseTypeSuffix != "" {
responseTypeSuffix = opts.ResponseTypeSuffix
}

// This creates the golang templates text package
TemplateFunctions["opts"] = func() Options { return opts }
t := template.New("oapi-codegen").Funcs(TemplateFunctions)
Expand Down
13 changes: 5 additions & 8 deletions pkg/codegen/template_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,14 @@ import (
const (
// These allow the case statements to be sorted later:
prefixMostSpecific, prefixLessSpecific, prefixLeastSpecific = "3", "6", "9"
responseTypeSuffix = "Response"
)

var (
contentTypesJSON = []string{echo.MIMEApplicationJSON, "text/x-json"}
contentTypesYAML = []string{"application/yaml", "application/x-yaml", "text/yaml", "text/x-yaml"}
contentTypesXML = []string{echo.MIMEApplicationXML, echo.MIMETextXML}

responseTypeSuffix = "Response"
)

// This function takes an array of Parameter definition, and generates a valid
Expand Down Expand Up @@ -149,9 +150,7 @@ func genResponseUnmarshal(op *OperationDefinition) string {
// JSON:
case StringInArray(contentTypeName, contentTypesJSON):
if typeDefinition.ContentTypeName == contentTypeName {
var caseAction string

caseAction = fmt.Sprintf("var dest %s\n"+
caseAction := fmt.Sprintf("var dest %s\n"+
"if err := json.Unmarshal(bodyBytes, &dest); err != nil { \n"+
" return nil, err \n"+
"}\n"+
Expand All @@ -166,8 +165,7 @@ func genResponseUnmarshal(op *OperationDefinition) string {
// YAML:
case StringInArray(contentTypeName, contentTypesYAML):
if typeDefinition.ContentTypeName == contentTypeName {
var caseAction string
caseAction = fmt.Sprintf("var dest %s\n"+
caseAction := fmt.Sprintf("var dest %s\n"+
"if err := yaml.Unmarshal(bodyBytes, &dest); err != nil { \n"+
" return nil, err \n"+
"}\n"+
Expand All @@ -181,8 +179,7 @@ func genResponseUnmarshal(op *OperationDefinition) string {
// XML:
case StringInArray(contentTypeName, contentTypesXML):
if typeDefinition.ContentTypeName == contentTypeName {
var caseAction string
caseAction = fmt.Sprintf("var dest %s\n"+
caseAction := fmt.Sprintf("var dest %s\n"+
"if err := xml.Unmarshal(bodyBytes, &dest); err != nil { \n"+
" return nil, err \n"+
"}\n"+
Expand Down
8 changes: 4 additions & 4 deletions pkg/codegen/templates/client-with-responses.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ type ClientWithResponsesInterface interface {
}

{{range .}}{{$opid := .OperationId}}{{$op := .}}
type {{$opid | ucFirst}}Response struct {
type {{genResponseTypeName $opid | ucFirst}} struct {
Body []byte
HTTPResponse *http.Response
{{- range getResponseTypeDefinitions .}}
Expand All @@ -49,15 +49,15 @@ type {{$opid | ucFirst}}Response struct {
}

// Status returns HTTPResponse.Status
func (r {{$opid | ucFirst}}Response) Status() string {
func (r {{genResponseTypeName $opid | ucFirst}}) Status() string {
if r.HTTPResponse != nil {
return r.HTTPResponse.Status
}
return http.StatusText(0)
}

// StatusCode returns HTTPResponse.StatusCode
func (r {{$opid | ucFirst}}Response) StatusCode() int {
func (r {{genResponseTypeName $opid | ucFirst}}) StatusCode() int {
if r.HTTPResponse != nil {
return r.HTTPResponse.StatusCode
}
Expand All @@ -70,7 +70,7 @@ func (r {{$opid | ucFirst}}Response) StatusCode() int {
{{$opid := .OperationId -}}
{{/* Generate client methods (with responses)*/}}

// {{$opid}}{{if .HasBody}}WithBody{{end}}WithResponse request{{if .HasBody}} with arbitrary body{{end}} returning *{{$opid}}Response
// {{$opid}}{{if .HasBody}}WithBody{{end}}WithResponse request{{if .HasBody}} with arbitrary body{{end}} returning *{{genResponseTypeName $opid}}
func (c *ClientWithResponses) {{$opid}}{{if .HasBody}}WithBody{{end}}WithResponse(ctx context.Context{{genParamArgs .PathParams}}{{if .RequiresParamObject}}, params *{{$opid}}Params{{end}}{{if .HasBody}}, contentType string, body io.Reader{{end}}, reqEditors... RequestEditorFn) (*{{genResponseTypeName $opid}}, error){
rsp, err := c.{{$opid}}{{if .HasBody}}WithBody{{end}}(ctx{{genParamNames .PathParams}}{{if .RequiresParamObject}}, params{{end}}{{if .HasBody}}, contentType, body{{end}}, reqEditors...)
if err != nil {
Expand Down
8 changes: 4 additions & 4 deletions pkg/codegen/templates/templates.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.