Skip to content

Commit

Permalink
Fix errors getting default env vars and Accept header (#9)
Browse files Browse the repository at this point in the history
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"
  • Loading branch information
tenczar authored Sep 27, 2018
1 parent ed41bad commit f30f5d5
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"net/http"
"os"
"os/signal"
"regexp"
"strconv"
"strings"

Expand Down Expand Up @@ -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 {
Expand All @@ -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
Expand All @@ -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)
}
Expand All @@ -91,9 +97,6 @@ func main() {
}

secrets := strings.Split(os.Getenv(secretsEnvVar), ",")
if len(secrets) == 0 {

}

rw := funky.NewDefaultHTTPReaderWriter(
funky.NewJSONHTTPMessageConverter(),
Expand Down Expand Up @@ -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))
}

0 comments on commit f30f5d5

Please sign in to comment.