当前位置: > > > > 关于 Unmarshal yaml into struct 的错误
关于 Unmarshal yaml into struct 的错误
来源:stackoverflow
2024-04-22 14:30:37
0浏览
收藏
大家好,今天本人给大家带来文章《关于 Unmarshal yaml into struct 的错误》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!
问题内容
我想解组一个 []byte 变量 int struct prometheusyml。以下是 promethuesyml 和 []byte 变量的定义。
type prometheusyml struct {
global global `yaml:"global,omitempty"`
scrapeconfigs []scrapeconfigs `yaml:"scrape_configs,omitempty"`
}
type global struct {
scrapeinterval string `yaml:"scrape_interval,omitempty"`
evaluationinterval string `yaml:"evaluation_interval,omitempty"`
}
type scrapeconfigs struct {
jobnmaes string `yaml:"job_name,omitempty"`
relabelconfigs []relabelconfigs `yaml:"relabel_configs,omitempty"`
metricspath string `yaml:"metrics_path,omitempty"`
scheme string `yaml:"scheme,omitempty"`
consulsdconfigs []consulsdconfigs `yaml:"consul_sd_configs,omitempty"`
}
type relabelconfigs struct {
sourcelabels string `yaml:"source_labels,omitempty"`
action string `yaml:"action,omitempty"`
regex string `yaml:"regex,omitempty"`
replacement string `yaml:"replacement,omitempty"`
targetlabel string `yaml:"target_label,omitempty"`
}
type consulsdconfigs struct {
server string `yaml:"server,omitempty"`
services []string `yaml:"services,omitempty"`
}
# my global config
global:
scrape_interval: 15s # set the scrape interval to every 15 seconds. default is every 1 minute.
evaluation_interval: 15s # evaluate rules every 15 seconds. the default is every 1 minute.
# scrape_timeout is set to the global default (10s).
scrape_configs:
- job_name: 'consul'
relabel_configs:
- source_labels: ["__meta_consul_service"]
action: replace
regex: "(.*)"
replacement: '${1}'
target_label: "service"
- source_labels: ["__meta_consul_tags"]
action: replace
regex: ',(?:[^,]+,){0}([^=]+)=([^,]+),.*'
replacement: '${2}'
target_label: '${1}'
- source_labels: ["__meta_consul_tags"]
action: replace
regex: ',(?:[^,]+,){1}([^=]+)=([^,]+),.*'
replacement: '${2}'
target_label: '${1}'
- source_labels: ["__meta_consul_tags"]
action: replace
regex: ',(?:[^,]+,){2}([^=]+)=([^,]+),.*'
replacement: '${2}'
target_label: '${1}'
metrics_path: /metrics
scheme: http
consul_sd_configs:
- server: 192.168.0.101:8500
services:
- cfs
但是当我运行该程序时。它显示了错误,这意味着无法将 source_labels 解组到结构中。很可能 [“__meta_consul_tags”] 无法翻译成字符串!!!!但我应该怎么做才能修复这个错误呢?实际类型是什么?
line 11: cannot unmarshal !!seq into string
解决方案
relabel_configs中的source_labels显然是string的数组。因此,您必须将 sourcelabels 的 数据类型 从 string 替换为 []string。那么你就可以开始了。
type relabelConfigs struct {
SourceLabels []string `yaml:"source_labels,omitempty"`
Action string `yaml:"action,omitempty"`
Regex string `yaml:"regex,omitempty"`
Replacement string `yaml:"replacement,omitempty"`
TargetLabel string `yaml:"target_label,omitempty"`
}
只需更改此即可解决您的问题。
今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注米云公众号,一起学习编程~
