Last active
June 20, 2020 15:09
-
-
Save nicolasparada/052948b158391c21a86ec252e6cb8e03 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"flag" | |
"log" | |
"net/http" | |
"os" | |
) | |
func main() { | |
allowedOrigin := os.Getenv("ALLOWED_ORIGIN") | |
flag.StringVar(&allowedOrigin, "allowed-origin", allowedOrigin, "Allowed origin to do requests to this server. If empty, anyone will have access") | |
flag.Parse() | |
mux := http.NewServeMux() | |
// define your routes here. | |
var h http.Handler = mux | |
{ | |
var opts []func(*accessControlOpts) | |
if allowedOrigin != "" { | |
opts = append(opts, accessControlWithOrigin(allowedOrigin)) | |
} | |
h = withAccessControl(h, opts...) | |
} | |
log.Fatalln(http.ListenAndServe(":8080", h)) | |
} | |
type accessControlOpts struct { | |
Origin *string | |
} | |
type accessControlOpt func(*accessControlOpts) | |
func accessControlWithOrigin(s string) accessControlOpt { | |
return func(opts *accessControlOpts) { | |
opts.Origin = &s | |
} | |
} | |
func withAccessControl(next http.Handler, opts ...func(*accessControlOpts)) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
h := w.Header() | |
h.Add("Vary", "Origin") | |
var options accessControlOpts | |
for _, o := range opts { | |
o(&options) | |
} | |
if options.Origin != nil { | |
h.Set("Access-Control-Allow-Origin", *options.Origin) | |
} else if origin := r.Header.Get("Origin"); origin != "" { | |
h.Set("Access-Control-Allow-Origin", origin) | |
} else { | |
h.Set("Access-Control-Allow-Origin", "*") | |
} | |
h.Set("Access-Control-Allow-Headers", "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type") | |
h.Set("Access-Control-Allow-Credentials", "true") | |
if r.Method == http.MethodOptions { | |
h.Add("Vary", "Access-Control-Request-Method") | |
h.Add("Vary", "Access-Control-Request-Headers") | |
h.Set("Access-Control-Allow-Methods", "HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS") | |
w.WriteHeader(http.StatusNoContent) | |
return | |
} | |
next.ServeHTTP(w, r) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment