-
Notifications
You must be signed in to change notification settings - Fork 125
/
options_handler_test.go
52 lines (42 loc) · 1.59 KB
/
options_handler_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package web
import (
"github.com/stretchr/testify/assert"
"strings"
"testing"
)
func TestOptionsHandler(t *testing.T) {
router := New(Context{})
sub := router.Subrouter(Context{}, "/sub")
sub.Middleware(AccessControlMiddleware)
sub.Get("/action", (*Context).A)
sub.Put("/action", (*Context).A)
rw, req := newTestRequest("OPTIONS", "/sub/action")
router.ServeHTTP(rw, req)
assertResponse(t, rw, "", 200)
assert.Equal(t, "GET, PUT", rw.Header().Get("Access-Control-Allow-Methods"))
assert.Equal(t, "*", rw.Header().Get("Access-Control-Allow-Origin"))
rw, req = newTestRequest("GET", "/sub/action")
router.ServeHTTP(rw, req)
assert.Equal(t, "*", rw.Header().Get("Access-Control-Allow-Origin"))
}
func TestCustomOptionsHandler(t *testing.T) {
router := New(Context{})
router.OptionsHandler((*Context).OptionsHandler)
sub := router.Subrouter(Context{}, "/sub")
sub.Middleware(AccessControlMiddleware)
sub.Get("/action", (*Context).A)
sub.Put("/action", (*Context).A)
rw, req := newTestRequest("OPTIONS", "/sub/action")
router.ServeHTTP(rw, req)
assertResponse(t, rw, "", 200)
assert.Equal(t, "GET, PUT", rw.Header().Get("Access-Control-Allow-Methods"))
assert.Equal(t, "100", rw.Header().Get("Access-Control-Max-Age"))
}
func (c *Context) OptionsHandler(rw ResponseWriter, req *Request, methods []string) {
rw.Header().Add("Access-Control-Allow-Methods", strings.Join(methods, ", "))
rw.Header().Add("Access-Control-Max-Age", "100")
}
func AccessControlMiddleware(rw ResponseWriter, req *Request, next NextMiddlewareFunc) {
rw.Header().Add("Access-Control-Allow-Origin", "*")
next(rw, req)
}