swaggo / swag

Automatically generate RESTful API documentation with Swagger 2.0 for Go.
MIT License
10.24k stars 1.17k forks source link

feat: Allow struct field type to differ from enum type #1804

Open alexrjones opened 3 months ago

alexrjones commented 3 months ago

Is your feature request related to a problem? Please describe. I have a custom type that functions like an enum. In memory it's a uint32, but in JSON, it's represented as its string value by way of a custom MarshalJSON method:

type MyEnumType uint32

const (
    MyEnumTypeFirst     = 1
    MyEnumTypeSecond    = 2
)

func (v MyEnumType) String() string {
    switch v {
    case MyEnumTypeFirst:   return "First"
    case MyEnumTypeSecond:  return "Second"
    }
    return fmt.Sprintf("MyEnumType(%d)", v)
}

func (v MyEnumType) MarshalJSON() ([]byte, error) {

    return []byte("\"" + v.String() + "\""), nil
}

type MyResponse struct {
    MyValue MyEnumType `json:"myValue"`
}

If I try to tag MyResponse.MyValue with enums:"First,Second", I get an error like:

ParseComment error in file ... mypackage.MyResponse: myValue: enum value First can't convert to integer err: strconv.Atoi: parsing "First": invalid syntax

Describe the solution you'd like Either:

Describe alternatives you've considered Representing MyEnumType as a string instead would work, but using uint32s with String() string methods to create enums is idiomatic in my project, so this would be a break from convention. It depends whether the maintainers are interested in supporting this behaviour.

Additional context I'd be happy to do the work to implement this myself but would first like to get input on which of the two solutions (if any) is preferred.