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
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,7 @@ public ModelsMap postProcessModels(ModelsMap objs) {

CodegenModel model = m.getModel();
if (model.isEnum) {
imports.add(createMapping("import", "fmt"));
continue;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,16 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re
{{^isDouble}}
{{^isLong}}
{{^isInteger}}
{{^isEnumOrRef}}
{{paramName}}Param := {{#routers}}{{#mux}}params["{{baseName}}"]{{/mux}}{{#chi}}chi.URLParam(r, "{{baseName}}"){{/chi}}{{/routers}}
{{/isEnumOrRef}}
{{#isEnumOrRef}}
{{paramName}}Param, err := New{{dataType}}FromValue({{#routers}}{{#mux}}params["{{baseName}}"]{{/mux}}{{#chi}}chi.URLParam(r, "{{baseName}}"){{/chi}}{{/routers}})
if err != nil {
c.errorHandler(w, r, &ParsingError{Err: err}, nil)
return
}
{{/isEnumOrRef}}
{{/isInteger}}
{{/isLong}}
{{/isDouble}}
Expand Down Expand Up @@ -329,7 +338,27 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re
{{^items.isDouble}}
{{^items.isLong}}
{{^items.isInteger}}
{{paramName}}Param := strings.Split(query.Get("{{baseName}}"), ",")
{{^items.isEnumRef}}
var {{paramName}}Param []string
if query.Has("{{baseName}}") {
{{paramName}}Param = strings.Split(query.Get("{{baseName}}"), ",")
}
{{/items.isEnumRef}}
{{#items.isEnumRef}}
var {{paramName}}Param []{{items.dataType}}
if query.Has("{{baseName}}") {
paramSplits := strings.Split(query.Get("{{baseName}}"), ",")
{{paramName}}Param = make([]{{items.dataType}}, 0, len(paramSplits))
for _, param := range paramSplits {
paramEnum, err := New{{items.dataType}}FromValue(param)
if err != nil {
c.errorHandler(w, r, &ParsingError{Err: err}, nil)
return
}
{{paramName}}Param = append({{paramName}}Param, paramEnum)
}
}
{{/items.isEnumRef}}
{{/items.isInteger}}
{{/items.isLong}}
{{/items.isDouble}}
Expand All @@ -346,11 +375,42 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re
{{#defaultValue}}
{{paramName}}Param := "{{defaultValue}}"
if query.Has("{{baseName}}") {
{{paramName}}Param = query.Get("{{baseName}}")
{{paramName}}Param = {{^isString}}{{dataType}}( {{/isString}}query.Get("{{baseName}}"){{^isString}} ){{/isString}}
}
{{/defaultValue}}
{{^defaultValue}}
{{^required}}
var {{paramName}}Param {{dataType}}
if query.Has("{{baseName}}") {
{{^isEnumOrRef}}
{{paramName}}Param = query.Get("{{baseName}}")
{{/isEnumOrRef}}
{{#isEnumOrRef}}
var err error
{{paramName}}Param, err = New{{dataType}}FromValue(query.Get("{{baseName}}"))
if err != nil {
c.errorHandler(w, r, &ParsingError{Err: err}, nil)
return
}
{{/isEnumOrRef}}
}
{{/required}}
{{#required}}
{{^isEnumOrRef}}
{{paramName}}Param := query.Get("{{baseName}}")
{{/isEnumOrRef}}
{{#isEnumOrRef}}
if !query.Has("{{baseName}}"){
c.errorHandler(w, r, &RequiredError{"{{baseName}}"}, nil)
return
}
{{paramName}}Param, err := New{{dataType}}FromValue(query.Get("{{baseName}}"))
if err != nil {
c.errorHandler(w, r, &ParsingError{Err: err}, nil)
return
}
{{/isEnumOrRef}}
{{/required}}
{{/defaultValue}}
{{/isArray}}
{{/isBoolean}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,44 @@ const (
{{#enumClassPrefix}}{{{classname.toUpperCase}}}_{{/enumClassPrefix}}{{name}} {{{classname}}} = {{{value}}}
{{/enumVars}}
{{/allowableValues}}
){{/isEnum}}{{^isEnum}}{{#description}}
)

// Allowed{{{classname}}}EnumValues is all the allowed values of {{{classname}}} enum
var Allowed{{{classname}}}EnumValues = []{{{classname}}}{
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we do a

map[{{classname}}]struct{}

That should work in O(1) time

Copy link
Contributor

@lwj5 lwj5 Oct 12, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me know if you need clarifications about this

Allowed{{{classname}}}EnumValues := map[myEnum]struct{}{
	"a": {},
	"b": {},
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I changed it to be a map. I had to add in a call to the golang maps package for the error message when an invalid Enum was provided.

{{#allowableValues}}
{{#enumVars}}
{{{value}}},
{{/enumVars}}
{{/allowableValues}}
}

// valid{{{classname}}}EnumValue provides a map of {{classname}}s for fast verification of use input
var valid{{{classname}}}EnumValues = map[{{{classname}}}]struct{}{
{{#allowableValues}}
{{#enumVars}}
{{{value}}}: {},
{{/enumVars}}
{{/allowableValues}}
}

// IsValid return true if the value is valid for the enum, false otherwise
func (v {{{classname}}}) IsValid() bool {
_, ok := valid{{{classname}}}EnumValues[v]
return ok
}

// New{{{classname}}}FromValue returns a pointer to a valid {{{classname}}}
// for the value passed as argument, or an error if the value passed is not allowed by the enum
func New{{{classname}}}FromValue(v {{{format}}}{{^format}}{{dataType}}{{/format}}) ({{{classname}}}, error) {
ev := {{{classname}}}(v)
if ev.IsValid() {
return ev, nil
} else {
return "", fmt.Errorf("invalid value '%v' for {{{classname}}}: valid values are %v", v, Allowed{{{classname}}}EnumValues)
}
}

{{/isEnum}}{{^isEnum}}{{#description}}
// {{classname}} - {{{description}}}{{/description}}
type {{classname}} struct {
{{#parent}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,52 @@ paths:
- petstore_auth:
- 'read:pets'
deprecated: true
'/pet/filterPets/{gender}':
get:
tags:
- pet
summary: Finds Pets
operationId: filterPetsByCategory
parameters:
- name: gender
in: path
required: true
schema:
$ref: '#/components/schemas/Gender'
- name: species
in: query
description: Species to filter by
required: true
style: form
explode: false
schema:
$ref: '#/components/schemas/Species'
- name: notSpecies
in: query
description: Species to omit from results
required: false
style: form
explode: false
schema:
type: array
items:
$ref: '#/components/schemas/Species'
responses:
'200':
description: successful operation
content:
application/xml:
schema:
type: array
items:
$ref: '#/components/schemas/Pet'
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Pet'
'400':
description: Invalid species value
'/pet/{petId}':
get:
tags:
Expand Down Expand Up @@ -810,6 +856,20 @@ components:
- sold
xml:
name: Pet
Species:
title: The species of a pet
type: string
enum:
- cat
- dog
- fish
- goat
- pig
Gender:
type: string
enum:
- male
- female
ApiResponse:
title: An uploaded response
description: Describes the result of uploading an image resource
Expand Down
10 changes: 8 additions & 2 deletions samples/openapi3/server/petstore/go/go-petstore/go/api_pet.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,10 @@ func (c *PetAPIController) DeletePet(w http.ResponseWriter, r *http.Request) {
// FindPetsByStatus - Finds Pets by status
func (c *PetAPIController) FindPetsByStatus(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
statusParam := strings.Split(query.Get("status"), ",")
var statusParam []string
if query.Has("status") {
statusParam = strings.Split(query.Get("status"), ",")
}
result, err := c.service.FindPetsByStatus(r.Context(), statusParam)
// If an error occurred, encode the error with the status code
if err != nil {
Expand All @@ -159,7 +162,10 @@ func (c *PetAPIController) FindPetsByStatus(w http.ResponseWriter, r *http.Reque
// Deprecated
func (c *PetAPIController) FindPetsByTags(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
tagsParam := strings.Split(query.Get("tags"), ",")
var tagsParam []string
if query.Has("tags") {
tagsParam = strings.Split(query.Get("tags"), ",")
}
result, err := c.service.FindPetsByTags(r.Context(), tagsParam)
// If an error occurred, encode the error with the status code
if err != nil {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@ go/logger.go
go/model_an_object.go
go/model_api_response.go
go/model_category.go
go/model_gender.go
go/model_order.go
go/model_order_info.go
go/model_pet.go
go/model_special_info.go
go/model_species.go
go/model_tag.go
go/model_user.go
go/routers.go
Expand Down
62 changes: 62 additions & 0 deletions samples/server/petstore/go-api-server/api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,54 @@ paths:
summary: Finds Pets by tags
tags:
- pet
/pet/filterPets/{gender}:
get:
operationId: filterPetsByCategory
parameters:
- explode: false
in: path
name: gender
required: true
schema:
$ref: '#/components/schemas/Gender'
style: simple
- description: Species to filter by
explode: false
in: query
name: species
required: true
schema:
$ref: '#/components/schemas/Species'
style: form
- description: Species to omit from results
explode: false
in: query
name: notSpecies
required: false
schema:
items:
$ref: '#/components/schemas/Species'
type: array
style: form
responses:
"200":
content:
application/xml:
schema:
items:
$ref: '#/components/schemas/Pet'
type: array
application/json:
schema:
items:
$ref: '#/components/schemas/Pet'
type: array
description: successful operation
"400":
description: Invalid species value
summary: Finds Pets
tags:
- pet
/pet/{petId}:
delete:
description: ""
Expand Down Expand Up @@ -987,6 +1035,20 @@ components:
type: object
xml:
name: Pet
Species:
enum:
- cat
- dog
- fish
- goat
- pig
title: The species of a pet
type: string
Gender:
enum:
- male
- female
type: string
ApiResponse:
description: Describes the result of uploading an image resource
example:
Expand Down
2 changes: 2 additions & 0 deletions samples/server/petstore/go-api-server/go/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
type PetAPIRouter interface {
AddPet(http.ResponseWriter, *http.Request)
DeletePet(http.ResponseWriter, *http.Request)
FilterPetsByCategory(http.ResponseWriter, *http.Request)
FindPetsByStatus(http.ResponseWriter, *http.Request)
// Deprecated
FindPetsByTags(http.ResponseWriter, *http.Request)
Expand Down Expand Up @@ -62,6 +63,7 @@ type UserAPIRouter interface {
type PetAPIServicer interface {
AddPet(context.Context, Pet) (ImplResponse, error)
DeletePet(context.Context, int64, string) (ImplResponse, error)
FilterPetsByCategory(context.Context, Gender, Species, []Species) (ImplResponse, error)
FindPetsByStatus(context.Context, []string) (ImplResponse, error)
// Deprecated
FindPetsByTags(context.Context, []string) (ImplResponse, error)
Expand Down
Loading