discord-gophers / goapi-gen

This package contains a set of utilities for generating Go boilerplate code for services based on OpenAPI 3.0 API definitions
Apache License 2.0
132 stars 12 forks source link

change enum MarshalJSON() method to not be called on ptr #99

Closed tiehm closed 1 year ago

tiehm commented 1 year ago

We have a bug in the current enum rendering system where the MarshalJSON method is never called on pointer structs. This fixes this behavior (quiet easily).

import (
    "encoding/json"
    "fmt"
)

type Enum struct {
    value string
}

type Enum2 struct {
    valie string
}

func (e Enum) MarshalJSON() ([]byte, error) {
    return []byte("\"another_value\""), nil
}

func (e *Enum2) MarshalJSON() ([]byte, error) {
    return []byte("\"another_value\""), nil
}

type Test struct {
    A Enum
    C Enum2
    B int
}

func main() {
    x := Test{
        A: Enum{},
        C: Enum2{},
        B: 1,
    }
    j, err := json.Marshal(x)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(j))
}

Prints:

{"A":"another_value","C":{},"B":1}

Go playground example: https://go.dev/play/p/8QQzFwO9a-K