Skip to content

Commit d59c877

Browse files
committed
add cors middleware method
1 parent 2685caf commit d59c877

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

middleware.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,17 @@ func (r *Router) Use(method string, middlewares ...interface{}) {
2121
}
2222
}
2323

24+
func CORSMiddleware() MiddlewareFunc {
25+
return func(handler Handler) Handler {
26+
return func(ctx *Context) error {
27+
ctx.Ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")
28+
ctx.Ctx.Response.Header.Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
29+
ctx.Ctx.Response.Header.Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
30+
return handler(ctx)
31+
}
32+
}
33+
}
34+
2435
func (m MiddlewareFunc) Handle(ctx *Context, next Handler) error {
2536
h := m(next)
2637
return h(ctx)

router_test.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,15 @@ import (
88
func TestRouterHandler(t *testing.T) {
99
router := New()
1010

11-
router.Get("/users/:id/:name", func(ctx *Context) error {
11+
router.Post("/users/:id/:name", func(ctx *Context) error {
1212
param := ctx.Param("name")
1313
ctx.String(param)
1414
ctx.String("hello")
1515
return nil
1616
})
1717

18+
router.Use("POST", CORSMiddleware())
19+
1820
err := fasthttp.ListenAndServe(":8083", RouterHandler(router))
1921
if err != nil {
2022
return

0 commit comments

Comments
 (0)