2

I am using Go Ent for ORM in my Go server.

The problem is, whenever I generate codes by custom schema, it makes all the fields with omitempty tag.

For example, this is my ent/schema/user.go.

type User struct {
    ent.Schema
}

// Fields of the Account.
func (User) Fields() []ent.Field {
    return []ent.Field{
        field.String("name").
            MaxLen(63).
            Unique(),
        field.Int32("money"),
    }
}

After I run the command go generate ./ent, it makes ent/user.go.

type User struct {
    config `json:"-"`
    // ID of the ent.
    ID int `json:"id,omitempty"`
    // Name holds the value of the "name" field.
    Name string `json:"name,omitempty"`
    // Money holds the value of the "money" field.
    Money int32 `json:"money,omitempty"`
}

I am using this *ent.User type as HTTP response body, but Money field has omitempty tag, so there is no money json field if the user has no money.

I know that replacing omitempty tag can be done with the following code, but I wanna replace this tag for all the fields I define at once.

type User struct {
    ent.Schema
}

// Fields of the Account.
func (User) Fields() []ent.Field {
    return []ent.Field{
        field.String("name").
            MaxLen(63).
            Unique(),
        field.Int32("money").
            StructTag("json:\"money\""),
    }
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Ellisein
  • 878
  • 6
  • 17

1 Answers1

0

You can loop over the fields and modify the descriptor:

func (User) Fields() []ent.Field {
    fields := []ent.Field{
        field.String("name").
            MaxLen(63).
            Unique(),
        field.Int32("money"),
    }
    for _, f := range fields {
        f.Descriptor().Tag = `json:"` + f.Descriptor().Name + `"`
    }
    return f
}

Or

func TrimOmitEmptyTag(fields []ent.Field) {
    for _, f := range fields {
        if f.Descriptor().Tag == "" {
            f.Descriptor().Tag = `json:"` + f.Descriptor().Name + `"`
        }
    }
}

func (User) Fields() []ent.Field {
    return TrimOmitEmptyTag([]ent.Field{
        field.String("name").
            MaxLen(63).
            Unique(),
        field.Int32("money").
            StructTag("json:\"money\""),
    })
}
dave
  • 62,300
  • 5
  • 72
  • 93