Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WriteJSON check response write error #1653

Closed
wants to merge 16 commits into from
34 changes: 34 additions & 0 deletions gin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"net/http"
"net/http/httptest"
"reflect"
"sync"
"testing"
"time"

Expand Down Expand Up @@ -500,3 +501,36 @@ func assertRoutePresent(t *testing.T, gotRoutes RoutesInfo, wantRoute RouteInfo)

func handlerTest1(c *Context) {}
func handlerTest2(c *Context) {}

func TestJSONErrorWrongContentLength(t *testing.T) {
router := New()
wg := sync.WaitGroup{}
wg.Add(1)
var globalError HandlerFunc = func(c *Context) {
defer func() {
if err := recover(); err != nil {
// catch c.JSON panic
assert.Equal(t, err, http.ErrContentLength)
}
c.JSON(http.StatusInternalServerError, "internal error")
wg.Done()
}()
c.Next()
}
router.Use(globalError)
router.GET("/testJson", func(c *Context) {
data := map[string]string{"name": "world"}
// write wrong content length number
// c.JSON will panic
c.Writer.Header().Set("Content-Length", "1")
c.JSON(http.StatusOK, data)
})
ts := httptest.NewServer(router)
defer ts.Close()

_, err := http.Get(fmt.Sprintf("%s/testJson", ts.URL))
if err != nil {
fmt.Println(err)
}
wg.Wait()
}