Beispiel #1
0
func TestDisallowedHeader(t *testing.T) {
	s := ctxcors.New(
		ctxcors.WithLogger(log.NewBlackHole()),
		ctxcors.WithAllowedOrigins("http://foobar.com"),
		ctxcors.WithAllowedHeaders("X-Header-1", "x-header-2"),
	)

	res := httptest.NewRecorder()
	req, _ := http.NewRequest("OPTIONS", "http://example.com/foo", nil)
	req.Header.Add("Origin", "http://foobar.com")
	req.Header.Add("Access-Control-Request-Method", "GET")
	req.Header.Add("Access-Control-Request-Headers", "X-Header-3, X-Header-1")

	s.WithCORS()(testHandler).ServeHTTPContext(context.Background(), res, req)

	assertHeaders(t, res.Header(), map[string]string{
		"Vary": "Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
		"Access-Control-Allow-Origin":      "",
		"Access-Control-Allow-Methods":     "",
		"Access-Control-Allow-Headers":     "",
		"Access-Control-Allow-Credentials": "",
		"Access-Control-Max-Age":           "",
		"Access-Control-Expose-Headers":    "",
	})
}
Beispiel #2
0
func TestAllowedOriginFunc(t *testing.T) {
	r, _ := regexp.Compile("^http://foo")
	s := ctxcors.New(
		ctxcors.WithLogger(log.NewBlackHole()),
		ctxcors.WithAllowOriginFunc(func(o string) bool {
			return r.MatchString(o)
		}),
	)

	req, _ := http.NewRequest("GET", "http://example.com/foo", nil)

	res := httptest.NewRecorder()
	req.Header.Set("Origin", "http://foobar.com")
	s.WithCORS()(testHandler).ServeHTTPContext(context.Background(), res, req)
	assertHeaders(t, res.Header(), map[string]string{
		"Access-Control-Allow-Origin": "http://foobar.com",
	})

	res = httptest.NewRecorder()
	req.Header.Set("Origin", "http://barfoo.com")
	s.WithCORS()(testHandler).ServeHTTPContext(context.Background(), res, req)
	assertHeaders(t, res.Header(), map[string]string{
		"Access-Control-Allow-Origin": "",
	})
}
Beispiel #3
0
func TestMatchAllOrigin(t *testing.T) {
	s := ctxcors.New(
		ctxcors.WithAllowedOrigins("*"),
		ctxcors.WithLogger(log.NewBlackHole()),
	)

	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
	req.Header.Add("Origin", "http://foobar.com")

	s.WithCORS()(testHandler)(context.Background(), res, req)

	assertHeaders(t, res.Header(), map[string]string{
		"Vary": "Origin",
		"Access-Control-Allow-Origin":      "http://foobar.com",
		"Access-Control-Allow-Methods":     "",
		"Access-Control-Allow-Headers":     "",
		"Access-Control-Allow-Credentials": "",
		"Access-Control-Max-Age":           "",
		"Access-Control-Expose-Headers":    "",
	})
}