小编kua*_*bin的帖子

yaml:解组错误:无法将字符串解组为 time.Duration 在 Golang

我有如下结构:

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 go unmarshalling

3
推荐指数
2
解决办法
6113
查看次数

在Golang中读取YAML文件,而YAML文件包含unicode字符(如"a\u0000b")

我在读取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)

string unicode yaml go

1
推荐指数
1
解决办法
720
查看次数

标签 统计

go ×2

yaml ×2

string ×1

unicode ×1

unmarshalling ×1