-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(middleware): add CORS middleware and refactor HTTP service
- Add new CorsMiddleware function in middleware/cors.go - Implement default CORS options with customization support - Replace direct usage of rs/cors in service/http.go with new middleware - Update HTTP service to use the new CorsMiddleware
- Loading branch information
Showing
2 changed files
with
44 additions
and
9 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
package middleware | ||
|
||
import ( | ||
"github.com/rs/cors" | ||
"net/http" | ||
) | ||
|
||
var defaultCorsOptions = cors.Options{ | ||
AllowOriginFunc: func(origin string) bool { | ||
return true | ||
}, | ||
AllowedMethods: []string{"GET", "POST", "PATCH", "DELETE", "HEAD", "OPTIONS"}, | ||
AllowedHeaders: []string{"*"}, | ||
AllowCredentials: true, | ||
} | ||
|
||
func CorsMiddleware(opts *cors.Options) func(h http.Handler) http.Handler { | ||
mergedOpts := defaultCorsOptions | ||
|
||
if opts != nil { | ||
if opts.AllowOriginFunc != nil { | ||
mergedOpts.AllowOriginFunc = opts.AllowOriginFunc | ||
} | ||
if len(opts.AllowedMethods) > 0 { | ||
mergedOpts.AllowedMethods = opts.AllowedMethods | ||
} | ||
if len(opts.AllowedHeaders) > 0 { | ||
mergedOpts.AllowedHeaders = opts.AllowedHeaders | ||
} | ||
if len(opts.ExposedHeaders) > 0 { | ||
mergedOpts.ExposedHeaders = opts.ExposedHeaders | ||
} | ||
if opts.AllowCredentials != mergedOpts.AllowCredentials { | ||
mergedOpts.AllowCredentials = opts.AllowCredentials | ||
} | ||
if opts.MaxAge > 0 { | ||
mergedOpts.MaxAge = opts.MaxAge | ||
} | ||
} | ||
|
||
return cors.New(mergedOpts).Handler | ||
} |
This file contains 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