Last active
August 29, 2015 14:12
-
-
Save quii/deb6d27a83aba3377e6f to your computer and use it in GitHub Desktop.
Generic configuration exposed over HTTP
This file contains 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 ( | |
"fmt" | |
"net/http" | |
"os" | |
"reflect" | |
"strings" | |
) | |
type ConfigServer struct { | |
values map[string]string | |
} | |
func (c *ConfigServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprint(w, c.values) | |
} | |
/* | |
This takes the address of your Config Struct and will try and get environment variable values for each | |
public field name. It then returns you a "config server" which you can then mount on to an endpoint | |
for debugging | |
*/ | |
func NewConfigServer(config interface{}) *ConfigServer { | |
c := new(ConfigServer) | |
c.values = make(map[string]string) | |
s := reflect.ValueOf(config).Elem() | |
typeOfKeys := s.Type() | |
for i := 0; i < s.NumField(); i++ { | |
fieldName := typeOfKeys.Field(i).Name | |
envValue := os.Getenv(strings.ToUpper(fieldName)) | |
f := s.Field(i) | |
f.SetString(envValue) | |
c.values[fieldName] = envValue | |
} | |
return c | |
} | |
/* | |
This struct can have any number of string fields with different names for your app | |
*/ | |
type FooFields struct { | |
Foo string | |
Bar string | |
} | |
func main() { | |
myConfig := FooFields{} | |
server := NewConfigServer(&myConfig) | |
fmt.Println(myConfig) | |
http.ListenAndServe(":8080", server) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment