简体   繁体   中英

How to read environment variables in JSON file using golang?

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

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

Here, {{$name}} is a placeholder

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:\n%v\n", 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM