亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《使用go将多行字符串写入yaml文件》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。
问题内容我需要将多行字符串作为值写入 go 中的 yaml 文件。当我整理数据时,我在数据中得到 \n ,如下所示。
apiversion: v1
name: td-agent-bit-config
namespace: logging
labels:
k8s-app: td-agent-bit-logging
data: "\n\tapiversion: v1\n\tkind: configmap\n\tmetadata:\n\tname: td-agent-bit-config\n\tnamespace:
se\n\tlabels:\n\t k8s-app: td-agent-bit-logging\n\tdata:"
如果我将其写为字符串,则会遇到缩进问题。
kind: configmap
metadata:
name: td-agent-bit-config
namespace: se
labels:
k8s-app: td-agent-bit-logging
data:
actinium.conf: |
[input]
name tail
buffer_max_size 3m
buffer_chunk_size 3m
mem_buf_limit 100mb
tag actinium.*```
我的 yaml 文件应该如下所示
kind: ConfigMap
metadata:
name: td-agent-bit-config
namespace: se
labels:
k8s-app: td-agent-bit-logging
data:
fluent-bit.conf: |
[SERVICE]
Flush 1
Log_Level info
Daemon off
@INCLUDE input-kubernetes.conf
@INCLUDE filter-kubernetes.conf
@INCLUDE output-kafka.conf
input-kubernetes.conf: |
[INPUT]
Name tail
Buffer_Max_Size 3M
Buffer_Chunk_Size 3M
Mem_Buf_Limit 100MB
Tag <serviceName>.*
Path /myntra/<serviceName>/logs/*/*
DB /var/log/<serviceName>.db
Refresh_Interval 10s
Rotate_Wait 10s
谁能帮忙解决这个问题吗?
正确答案
我不知道你如何编组/解组 yaml
但是如果你使用https://github.com/go-yaml/yaml就没有问题(去get gopkg.in/yaml.v2)
package main
import (
"fmt"
"log"
"gopkg.in/yaml.v2"
)
var data = `
a: easy!
b:
c: 2
d: [3, 4]
e: |
[service]
flush 1
log_level info
daemon off
@include input-kubernetes.conf
@include filter-kubernetes.conf
@include output-kafka.conf
`
// note: struct fields must be public in order for unmarshal to
// correctly populate the data.
type t struct {
a string
b struct {
renamedc int `yaml:"c"`
d []int `yaml:",flow"`
}
e string
}
func main() {
t := t{}
err := yaml.unmarshal([]byte(data), &t)
if err != nil {
log.fatalf("error: %v", err)
}
fmt.printf("--- t:\n%v\n\n", t)
d, err := yaml.marshal(&t)
if err != nil {
log.fatalf("error: %v", err)
}
fmt.printf("--- t dump:\n%s\n\n", string(d))
}
--- t:
{Easy! {2 [3 4]} [SERVICE]
Flush 1
Log_Level info
Daemon off
@INCLUDE input-kubernetes.conf
@INCLUDE filter-kubernetes.conf
@INCLUDE output-kafka.conf
}
--- t dump:
a: Easy!
b:
c: 2
d: [3, 4]
e: |
[SERVICE]
Flush 1
Log_Level info
Daemon off
@INCLUDE input-kubernetes.conf
@INCLUDE filter-kubernetes.conf
@INCLUDE output-kafka.conf
终于介绍完啦!小伙伴们,这篇关于《使用go将多行字符串写入yaml文件》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~编程网公众号也会发布Golang相关知识,快来关注吧!