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

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

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

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

	assert.Equal(t, httputil.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{}.ServeHTTPContext,
		ctxmw.WithXHTTPMethodOverride())
	w := httptest.NewRecorder()
	req, err := http.NewRequest(httputil.MethodGet, "http://example.com/foo?_method="+httputil.MethodPatch, nil)
	assert.NoError(t, err)
	assert.NoError(t, hndlr.ServeHTTPContext(context.Background(), w, req))
	assert.Equal(t, httputil.MethodPatch, req.Method)
	assert.Equal(t, "h1 called", w.Body.String())

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

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

}