Skip to content

Commit

Permalink
Merge pull request #10 from swaggest/enum-tag
Browse files Browse the repository at this point in the history
Support `enum` field tag
  • Loading branch information
vearutop authored Nov 8, 2018
2 parents 330ed13 + eca2c36 commit 3cc2fb5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 14 deletions.
39 changes: 32 additions & 7 deletions entities.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"net/http"
"reflect"
"strings"
)

Expand Down Expand Up @@ -31,7 +32,6 @@ type Document struct {
additionalData
}


// MarshalJSON marshal Document with additionalData inlined
func (s Document) MarshalJSON() ([]byte, error) {
type i Document
Expand Down Expand Up @@ -247,13 +247,38 @@ type Enum struct {
EnumNames []string `json:"x-enum-names,omitempty"`
}

type namedEnum interface {
// NamedEnum return the const-name pair slice
NamedEnum() ([]interface{}, []string)
}
// LoadFromField loads enum from field tag: json array or comma-separated string
func (enum *Enum) LoadFromField(field reflect.StructField) {
type namedEnum interface {
// NamedEnum return the const-name pair slice
NamedEnum() ([]interface{}, []string)
}

type plainEnum interface {
Enum() []interface{}
}


type enum interface {
Enum() []interface{}
if e, isEnumer := reflect.Zero(field.Type).Interface().(namedEnum); isEnumer {
enum.Enum, enum.EnumNames = e.NamedEnum()
}

if e, isEnumer := reflect.Zero(field.Type).Interface().(plainEnum); isEnumer {
enum.Enum = e.Enum()
}

if enumTag := field.Tag.Get("enum"); enumTag != "" {
var e []interface{}
err := json.Unmarshal([]byte(enumTag), &e)
if err != nil {
es := strings.Split(enumTag, ",")
e = make([]interface{}, len(es))
for i, s := range es {
e[i] = s
}
}
enum.Enum = e
}
}

// SwaggerData holds parameter and schema information for swagger definition
Expand Down
11 changes: 4 additions & 7 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,9 @@ func (g *Generator) parseDefinitionProperties(v reflect.Value, parent *SchemaObj
}

}

obj.Enum.LoadFromField(field)

if formatTag := field.Tag.Get("format"); formatTag != "" {
obj.Format = formatTag
}
Expand Down Expand Up @@ -549,13 +552,7 @@ func (g *Generator) ParseParameters(i interface{}) (string, []ParamObj) {

param.Name = paramName

if e, isEnumer := reflect.Zero(field.Type).Interface().(namedEnum); isEnumer {
param.Enum.Enum, param.Enum.EnumNames = e.NamedEnum()
}

if e, isEnumer := reflect.Zero(field.Type).Interface().(enum); isEnumer {
param.Enum.Enum = e.Enum()
}
param.Enum.LoadFromField(field)

if descTag := field.Tag.Get("description"); descTag != "-" && descTag != "" {
param.Description = descTag
Expand Down

0 comments on commit 3cc2fb5

Please sign in to comment.