drzip28288 2018-07-18 15:55
浏览 365

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

Is there any way to put placeholders in json file which we can dynamically fill with values? for e.g.,

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

Here, {{$name}} is a placeholder

  • 写回答

1条回答 默认 最新

  • duanjuelian4640 2018-07-18 16:25
    关注

    Yes, you should be able to achieve this by using text/template https://golang.org/pkg/text/template/

    You will then be able to define json template files, for example:

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

    Let's assume the following data structure:

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

    To utilize the template:

    // 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:
    %v
    ", ts.String())
    

    The code above should produce the following output:

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

    Your template variable names must correspond to the exported values of the data struct you pass to Execute. The example password hash is 10 rounds of bcrypt on the string "BadPassword123". Using the bytes. Buffer allows for flexible use such as passing over the network, writing to file, or displaying to console using the String() function.

    For environment variables I would recommend the second approach, namely the golang map:

    // 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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?