Skip to content

Commit

Permalink
[cors] add OPTIONS status code + fix function typo
Browse files Browse the repository at this point in the history
  • Loading branch information
commit-master committed Aug 28, 2018
1 parent 7e0847f commit 2b29c06
Showing 1 changed file with 20 additions and 6 deletions.
26 changes: 20 additions & 6 deletions cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,16 @@ type cors struct {
maxAge int
ignoreOptions bool
allowCredentials bool
optionStatusCode int
}

// OriginValidator takes an origin string and returns whether or not that origin is allowed.
type OriginValidator func(string) bool

var (
defaultCorsMethods = []string{"GET", "HEAD", "POST"}
defaultCorsHeaders = []string{"Accept", "Accept-Language", "Content-Language", "Origin"}
defaultCorsOptionStatusCode = 200
defaultCorsMethods = []string{"GET", "HEAD", "POST"}
defaultCorsHeaders = []string{"Accept", "Accept-Language", "Content-Language", "Origin"}
// (WebKit/Safari v9 sends the Origin header by default in AJAX requests)
)

Expand Down Expand Up @@ -130,6 +132,7 @@ func (ch *cors) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set(corsAllowOriginHeader, returnOrigin)

if r.Method == corsOptionMethod {
w.WriteHeader(ch.optionStatusCode)
return
}
ch.h.ServeHTTP(w, r)
Expand Down Expand Up @@ -164,9 +167,10 @@ func CORS(opts ...CORSOption) func(http.Handler) http.Handler {

func parseCORSOptions(opts ...CORSOption) *cors {
ch := &cors{
allowedMethods: defaultCorsMethods,
allowedHeaders: defaultCorsHeaders,
allowedOrigins: []string{},
allowedMethods: defaultCorsMethods,
allowedHeaders: defaultCorsHeaders,
allowedOrigins: []string{},
optionStatusCode: defaultCorsOptionStatusCode,
}

for _, option := range opts {
Expand Down Expand Up @@ -251,7 +255,17 @@ func AllowedOriginValidator(fn OriginValidator) CORSOption {
}
}

// ExposeHeaders can be used to specify headers that are available
// OptionStatusCode sets a custom status code to use to respond to OPTIONS requests
// by default it is set to 200 to ensure max compatibility, see:
// https://stackoverflow.com/questions/46026409/what-are-proper-status-codes-for-cors-preflight-requests
func OptionStatusCode(code int) CORSOption {
return func(ch *cors) error {
ch.optionStatusCode = code
return nil
}
}

// ExposedHeaders can be used to specify headers that are available
// and will not be stripped out by the user-agent.
func ExposedHeaders(headers []string) CORSOption {
return func(ch *cors) error {
Expand Down

0 comments on commit 2b29c06

Please sign in to comment.