Skip to content

Instantly share code, notes, and snippets.

@naveensrinivasan
Created June 23, 2013 22:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naveensrinivasan/5846791 to your computer and use it in GitHub Desktop.
Save naveensrinivasan/5846791 to your computer and use it in GitHub Desktop.
Here is a code to get the environment variables as a map in go instead of slice.
package main
import (
"fmt"
"os"
"strings"
)
func main() {
getenvironment := func(data []string, getkeyval func(item string) (key, val string)) map[string]string {
items := make(map[string]string)
for _, item := range data {
key, val := getkeyval(item)
items[key] = val
}
return items
}
environment := getenvironment(os.Environ(), func(item string) (key, val string) {
splits := strings.Split(item, "=")
key = splits[0]
val = splits[1]
return
})
fmt.Println(environment["KEY"])
}
@seunggabi
Copy link

seunggabi commented Aug 24, 2022

awesome!

how it is?

package main

import (
	"os"
	"strings"
	"text/template"
)

func Format(s string, v interface{}) string {
	t, b := new(template.Template), new(strings.Builder)
	template.Must(t.Parse(s)).Execute(b, v)

	result := b.String()
	if result == "<no value>" {
		return s
	}

	return result
}

func KeyValue(item string) (key, val string) {
	splits := strings.Split(item, "=")
	key = splits[0]
	val = splits[1]
	return
}

func Env() map[string]string {
	data := os.Environ()

	items := make(map[string]string)
	for _, item := range data {
		key, val := KeyValue(item)
		items[key] = val
	}

	return items
}

func main() {
	response := Format("{{ .asdf }}", Env())

	println(response)
}

@limao693
Copy link

limao693 commented Sep 1, 2022

a=b=c want: a b=c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment