mercredi 11 mai 2022

Cannot get method by reflect when defining a new type from an existing type

I use type declarations to custom type within gorm, the following code works fine:

type LocalTime time.Time

func (t LocalTime) MarshalJSON() ([]byte, error) {
    pt := time.Time(t)
    return []byte(fmt.Sprintf("\"%s\"", pt.Format("2006-01-02 15:04:05"))), nil
}
// ...etc

When I need to further more work with gocsv, matters come.

func (t *LocalTime) MarshalCSV() (string, error) {
    s, err := t.MarshalJSON()
    return string(s), err
}

type APIInfo struct {
    ID            uint64         `gorm:"type:bigint unsigned AUTO_INCREMENT;primaryKey;column:id" json:"-" csv:"-"`
    AccessTime    LocalTime      `gorm:"column:access_time" json:"access_time" csv:"access_time"`      
}

var infos []*APIInfo
// ...
gocsv.MarshalBytes(infos)

gocsv use reflect to detect whether a custom type has MarshalCSV method like below

reflect.TypeOf(localTime).MethodByName("MarshalCSV")

In this case, reflect.TypeOf(localTime) will return type of time.Time, which doesn't have MarshalCSV.

How can I fix it with as little damage to the existing code as possible?





Aucun commentaire:

Enregistrer un commentaire