Created
March 29, 2016 13:34
-
-
Save raphink/e1afb23300a7e53a0949 to your computer and use it in GitHub Desktop.
Access environment variables in a Go template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"os" | |
"strings" | |
) | |
func main() { | |
const tmpl := ` | |
USER={{.USER}} | |
HOME={{.HOME}} | |
` | |
envMap, _ := envToMap() | |
t := template.Must(template.New("tmpl").Parse(tmpl)) | |
t.Execute(os.Stdout, envMap) | |
} | |
func envToMap() (map[string]string, error) { | |
envMap := make(map[string]string) | |
var err error | |
for _, v := range os.Environ() { | |
split_v := strings.Split(v, "=") | |
envMap[split_v[0]] = split_v[1] | |
} | |
return envMap, err | |
} |
Actually it might be better to use
split_v := strings.SplitN(v, "=", 2)
That way you don't have to join the strings later on
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this code drops loot. L25 should be: