示例#1
0
func TestAdapters(t *testing.T) {

	hndlr := ctxhttp.Chain(
		h1{},
		ctxhttp.WithXHTTPMethodOverride(),
		ctxhttp.WithHeader("X-Men", "Y-Women"),
	)

	w := httptest.NewRecorder()
	req, err := http.NewRequest(httputils.MethodGet, "http://example.com/foo", nil)
	req.Header.Set(httputils.MethodOverrideHeader, httputils.MethodPut)
	assert.NoError(t, err)

	a := ctxhttp.NewAdapter(context.Background(), hndlr)
	a.ServeHTTP(w, req)

	assert.Equal(t, httputils.MethodPut, req.Method)
	assert.Equal(t, "h1 called", w.Body.String())
	assert.Equal(t, "Y-Women", w.Header().Get("X-Men"))
}
示例#2
0
func TestHttpMethodOverride(t *testing.T) {
	hndlr := ctxhttp.Chain(
		h1{},
		ctxhttp.WithXHTTPMethodOverride())
	w := httptest.NewRecorder()
	req, err := http.NewRequest(httputils.MethodGet, "http://example.com/foo?_method="+httputils.MethodPatch, nil)
	assert.NoError(t, err)
	hndlr.ServeHTTPContext(context.Background(), w, req)
	assert.Equal(t, httputils.MethodPatch, req.Method)
	assert.Equal(t, "h1 called", w.Body.String())

	w = httptest.NewRecorder()
	req, err = http.NewRequest(httputils.MethodGet, "http://example.com/foo?_method=KARATE", nil)
	assert.NoError(t, err)
	hndlr.ServeHTTPContext(context.Background(), w, req)
	assert.Equal(t, httputils.MethodGet, req.Method)

	w = httptest.NewRecorder()
	req, err = http.NewRequest(httputils.MethodGet, "http://example.com/foobar", nil)
	assert.NoError(t, err)
	hndlr.ServeHTTPContext(context.Background(), w, req)
	assert.Equal(t, httputils.MethodGet, req.Method)

}