gpt4 book ai didi

json - 如何使用golang读取JSON文件中的环境变量?

转载 作者:IT王子 更新时间:2023-10-29 02:37:18 27 4
gpt4 key购买 nike

有什么方法可以将占位符放在我们可以动态填充值的 json 文件中吗?例如,

{
"name": "{{$name}}"
}

这里,{{$name}}是一个占位符

最佳答案

是的,你应该能够通过使用文本/模板来实现这一点 https://golang.org/pkg/text/template/

然后您将能够定义 json 模板文件,例如:

// JSON file: user.tpl.json
{
"username": "{{ .Username }}",
"password": "{{ .PasswordHash }}",
"email": "{{ Email }}",
}

让我们假设以下数据结构:

type User struct {
Username string
Password []byte // use a properly hashed password (bcrypt / scrypt)
Email string
}

使用模板:

// parse the template
tpl, err := template.ParseFiles("user.tpl.json")
if err != nil {
log.Fatal(err)
}

// define some data for the template, you have 2 options here:
// 1. define a struct with exported fields,
// 2. use a map with keys corresponding to the template variables
u := User {
Username: "ThereIsNoSpoon",
Password: pwdHash, // obtain proper hash using bcrypt / scrypt
Email: nospoon@me.com,
}

// execute the template with the given data
var ts bytes.Buffer
err = tpl.Execute(&ts, u) // Execute will fill the buffer so pass as reference
if err != nil {
log.Fatal(err)
}

fmt.Printf("User JSON:\n%v\n", ts.String())

上面的代码应该产生以下输出:

User JSON:
{
"username": "ThereIsNoSpoon",
"Password": "$2a$10$SNCKzLpj/AqBJSjVEF315eAwbsAM7nZ0e27poEhjhj9rHG3LkZzxS",
"Email": "nospoon@me.com"
}

您的模板变量名称必须与您传递给 Execute 的数据结构的导出值相对应。示例密码哈希是字符串“BadPassword123”上的 10 轮 bcrypt。使用字节。缓冲区允许灵活使用,例如通过网络传递、写入文件或使用 String() 函数显示到控制台。

对于环境变量,我会推荐第二种方法,即 golang 映射:

// declare a map that will serve as the data structure between environment
// variables and the template
dmap := make(map[string]string)

// insert environment variables into the map using a key relevant to the
// template
dmap["Username"] = os.GetEnv("USER")
// ...

// execute template by passing the map instead of the struct

关于json - 如何使用golang读取JSON文件中的环境变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51406335/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com