From f30f5d5b1251606d43aeccb012c707943751ce39 Mon Sep 17 00:00:00 2001 From: tenczar Date: Thu, 27 Sep 2018 15:15:50 -0700 Subject: [PATCH] Fix errors getting default env vars and Accept header (#9) Now properly defaults if TIMEOUT and SERVER environment variables aren't set. Also properly returns json when the Accept header is empty, "application/*" or "application/json" --- main.go | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/main.go b/main.go index 447c49d..34edb85 100644 --- a/main.go +++ b/main.go @@ -12,6 +12,7 @@ import ( "net/http" "os" "os/signal" + "regexp" "strconv" "strings" @@ -51,11 +52,16 @@ func (f funkyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { resp, _ := f.router.Delegate(body) - accept := "application/json" - if r.Header.Get("Accept") != "" { - accept = r.Header.Get("Accept") + accept := r.Header.Get("Accept") + matched, err := regexp.Match("(application|\\*)\\/(json|\\*)|^$", []byte(accept)) + if matched { + accept = "application/json" + } + + err = f.rw.Write(resp, accept, w) + if err != nil { + fmt.Fprintf(w, "Unsupported Accept type: %s", accept) } - f.rw.Write(resp, accept, w) } func healthy(c <-chan struct{}) bool { @@ -68,9 +74,9 @@ func healthy(c <-chan struct{}) bool { } func main() { - numServers, err := strconv.Atoi(os.Getenv(serversEnvVar)) + numServers, err := envVarGetInt(serversEnvVar, 1) if err != nil { - log.Fatalf("Unable to parse %s environment variable", serversEnvVar) + log.Fatalf("Unable to parse %s environment variable to int", serversEnvVar) } if numServers < 1 { numServers = 1 @@ -82,7 +88,7 @@ func main() { log.Fatal("Too few arguments to server command.") } - funcTimeout, err := strconv.Atoi(os.Getenv(timeoutEnvVar)) + funcTimeout, err := envVarGetInt(timeoutEnvVar, 0) if err != nil { log.Fatalf("Unable to parse %s environment variable to int", timeoutEnvVar) } @@ -91,9 +97,6 @@ func main() { } secrets := strings.Split(os.Getenv(secretsEnvVar), ",") - if len(secrets) == 0 { - - } rw := funky.NewDefaultHTTPReaderWriter( funky.NewJSONHTTPMessageConverter(), @@ -147,3 +150,11 @@ func main() { server.ListenAndServe() } + +func envVarGetInt(envVar string, orElse int) (int, error) { + if os.Getenv(envVar) == "" { + return orElse, nil + } + + return strconv.Atoi(os.Getenv(envVar)) +}