From 4f855faef2b0b87b51fe03e71f0e07aea3e45ea3 Mon Sep 17 00:00:00 2001 From: Manu Mtz-Almeida Date: Tue, 19 May 2015 22:18:58 +0200 Subject: [PATCH] Adds helper function. Wrap(http.HandlerFund) gin.HandlerFun --- utils.go | 7 +++++++ utils_test.go | 17 +++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/utils.go b/utils.go index e4d144fc..476eb832 100644 --- a/utils.go +++ b/utils.go @@ -6,12 +6,19 @@ package gin import ( "encoding/xml" + "net/http" "path" "reflect" "runtime" "strings" ) +func Wrap(f http.HandlerFunc) HandlerFunc { + return func(c *Context) { + f(c.Writer, c.Request) + } +} + type H map[string]interface{} // Allows type H to be used with xml.Marshal diff --git a/utils_test.go b/utils_test.go index 676b6b87..5bd4cc15 100644 --- a/utils_test.go +++ b/utils_test.go @@ -5,6 +5,8 @@ package gin import ( + "fmt" + "net/http" "testing" "github.com/stretchr/testify/assert" @@ -14,6 +16,21 @@ func init() { SetMode(TestMode) } +func TestWrap(t *testing.T) { + router := New() + router.GET("/path", Wrap(func(w http.ResponseWriter, req *http.Request) { + assert.Equal(t, req.Method, "GET") + assert.Equal(t, req.URL.Path, "/path") + w.WriteHeader(400) + fmt.Fprint(w, "hola!") + })) + + w := performRequest(router, "GET", "/path") + + assert.Equal(t, w.Code, 400) + assert.Equal(t, w.Body.String(), "hola!") +} + func TestLastChar(t *testing.T) { assert.Equal(t, lastChar("hola"), uint8('a')) assert.Equal(t, lastChar("adios"), uint8('s'))