Ver código fonte

Adds helper function. Wrap(http.HandlerFund) gin.HandlerFun

Manu Mtz-Almeida 10 anos atrás
pai
commit
4f855faef2
2 arquivos alterados com 24 adições e 0 exclusões
  1. 7 0
      utils.go
  2. 17 0
      utils_test.go

+ 7 - 0
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

+ 17 - 0
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'))