我有如下结构:
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'
`
Run Code Online (Sandbox Code Playgroud)
如上图,超时类型为time.Duration,默认单位为纳秒,但我想得到结果:c1 && c2有错误,c3 && c4有效(超时配置必须有单位)。我应该如何重写 yaml 的 UnmarshalYAML() 方法?非常感谢。
我在读取YAML文件时遇到问题,YAML文件包含Unicode字符转义.但是当我加载YAML文件并打印时fileInfo,包含Unicode字符转义(例如'a\u0000b')的字符串在使用unMarshal()函数时被转义.
这是我的YAML文件(conf.yml):
topicList:
- source: 'test'
target: 'temp'
- source: 'a\u0000b'
target: 'temp'
Run Code Online (Sandbox Code Playgroud)
我的代码是:
import (
"fmt"
"io/ioutil"
"strings"
"gopkg.in/yaml.v2"
)
type Config struct {
TopicList []Topic `yaml:"topicList"`
}
type Topic struct {
Source string `yaml:"source" json:"source"`
Target string `yaml:"target" json:"target"`
}
func main() {
cfg, err := NewConfig("conf.yml")
if err != nil {
fmt.Println("load config fail: ", err)
}
for _, s := range cfg.TopicList {
fmt.Println("\n +++++ sourceTopic = ", …Run Code Online (Sandbox Code Playgroud)