-
-
Save 0xack13/4f7fbaeddfa8c9fc14666e9833012e42 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 | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment