Skip to content

Commit

Permalink
cors fallbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
ghostec committed Oct 2, 2017
1 parent 92f93dd commit 23b25fa
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions api/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,31 @@ func (rw *responseWriter) WriteHeader(code int) {
rw.ResponseWriter.WriteHeader(code)
}

func corsAllowedFallback(envvar, fallback string) []string {
val, prs := os.LookupEnv(envvar)
if prs == false {
val = fallback
}
return strings.Split(val, " ")
}

func corsAllowedOrigins() []string {
return corsAllowedFallback("CORS_ALLOWED_ORIGINS", "*")
}

func corsAllowedMethods() []string {
return corsAllowedFallback("CORS_ALLOWED_METHODS", "GET PUT POST DELETE")
}

func corsAllowedHeaders() []string {
return corsAllowedFallback("CORS_ALLOWED_HEADERS", "authorization")
}

func wrapHandlerWithResponseWriter(wrappedHandler http.Handler) http.Handler {
c := cors.New(cors.Options{
AllowedOrigins: strings.Split(os.Getenv("CORS_ALLOWED_ORIGINS"), " "),
AllowedMethods: strings.Split(os.Getenv("CORS_ALLOWED_METHODS"), " "),
AllowedHeaders: strings.Split(os.Getenv("CORS_ALLOWED_HEADERS"), " "),
AllowedOrigins: corsAllowedOrigins(),
AllowedMethods: corsAllowedMethods(),
AllowedHeaders: corsAllowedHeaders(),
})

return c.Handler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
Expand Down

0 comments on commit 23b25fa

Please sign in to comment.