我有如下結(jié)構(gòu):type Connect struct { ClientID string `yaml:"clientid"` Password string `yaml:"password"` Timeout time.Duration `yaml:"timeout"`}c1 := ` id: 'client1' password: 'hhhhhhha' timeout: 10 `c2 := ` id: 'client2' password: 'llllllla' timeout: '10' `c3 := ` id: 'client3' password: 'hhhhhhha' timeout: 10s `c4 := ` id: 'client4' password: 'llllllla' timeout: '10s' `如上所示,Timeout的類型為time.Duration,默認(rèn)單位為納秒,但我想得到結(jié)果:c1 && c2有錯誤,c3 && c4有效(Timeout的配置必須具有unit)。如何為yaml重寫UnmarshalYAML()方法?非常感謝。
3 回答

翻翻過去那場雪
TA貢獻(xiàn)2065條經(jīng)驗 獲得超14個贊
一種方法是為Timeout實現(xiàn)Unmarshaler接口的自定義類型創(chuàng)建一個方法,如果您不能使用以下UnmarshalYAML方法實現(xiàn)該功能Connect:
type Connect struct {
ClientID string `yaml:"clientid"`
Password string `yaml:"password"`
Timeout UnmarshalingTimeout `yaml:"timeout"`
}
type UnmarshalingTimeout time.Duration
func (ut UnmarshalingTimeout) UnmarshalYAML(unmarshal func(interface{}) error) error {
// implement unmarshaling here
}
- 3 回答
- 0 關(guān)注
- 551 瀏覽
添加回答
舉報
0/150
提交
取消