Skip to content

Commit

Permalink
♻️ refactor: renew cors #36
Browse files Browse the repository at this point in the history
  • Loading branch information
pnguyen215 committed Oct 24, 2023
1 parent 6d351b4 commit b83a741
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion corsx/cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func (c *CorsConfig) Json() string {
func GetCorsConfigSample() *CorsConfig {
c := NewCorsConfig().
SetEnabled(true).
SetMaxAge(0).
SetMaxAge(3600).
SetAllowCredentials(true).
AppendAllowedOrigins("*").
AppendAllowedMethods(restify.MethodGet, restify.MethodPost, restify.MethodPut, restify.MethodDelete, restify.MethodOptions).
Expand All @@ -102,6 +102,10 @@ func (c *CorsConfig) ApplyCorsHeaders(w http.ResponseWriter, r *http.Request) {
w.Header().Set(common.HeaderAccessControlAllowMethods, strings.Join(c.AllowedMethods, ","))
w.Header().Set(common.HeaderAccessControlAllowHeaders, strings.Join(c.AllowedHeaders, ","))
w.Header().Set(common.HeaderAccessControlExposeHeaders, strings.Join(c.ExposedHeaders, ","))
if r.Method == http.MethodOptions { // handle preflight request
w.WriteHeader(http.StatusOK)
return
}
if c.AllowCredentials {
w.Header().Set(common.HeaderAccessControlAllowCredentials, strconv.FormatBool(c.AllowCredentials))
}
Expand All @@ -111,6 +115,13 @@ func (c *CorsConfig) ApplyCorsHeaders(w http.ResponseWriter, r *http.Request) {
}
}

func (c *CorsConfig) CoreMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c.ApplyCorsHeaders(w, r)
next.ServeHTTP(w, r)
})
}

// isOriginAllowed checks if the provided origin is allowed based on the configuration.
func (c *CorsConfig) isOriginAllowed(origin string) bool {
for _, allowedOrigin := range c.AllowedOrigins {
Expand Down

0 comments on commit b83a741

Please sign in to comment.