登录
首页 >  Golang >  Go问答

使用golang从JSON文件中提取环境变量的方法

来源:stackoverflow

时间:2024-03-14 13:18:26 194浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《使用golang从JSON文件中提取环境变量的方法》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

有什么方法可以将占位符放入 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: [email protected],
}

// 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": "[email protected]"
}

您的模板变量名称必须与您传递给执行的数据结构的导出值相对应。示例密码哈希是对字符串“badpassword123”进行 10 轮 bcrypt。使用字节。 buffer 允许灵活使用,例如通过网络传递、写入文件或使用 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

今天关于《使用golang从JSON文件中提取环境变量的方法》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>