mirror of
https://github.com/gin-gonic/gin.git
synced 2025-05-21 17:37:04 +08:00
feat: add SecureJSON func to prevent json hijacking
This commit is contained in:
@ -66,6 +66,31 @@ func TestRenderIndentedJSON(t *testing.T) {
|
||||
assert.Equal(t, w.Header().Get("Content-Type"), "application/json; charset=utf-8")
|
||||
}
|
||||
|
||||
func TestRenderSecureJSON(t *testing.T) {
|
||||
w1 := httptest.NewRecorder()
|
||||
data := map[string]interface{}{
|
||||
"foo": "bar",
|
||||
}
|
||||
|
||||
err1 := (SecureJSON{"while(1);", data}).Render(w1)
|
||||
|
||||
assert.NoError(t, err1)
|
||||
assert.Equal(t, "{\"foo\":\"bar\"}", w1.Body.String())
|
||||
assert.Equal(t, "application/json; charset=utf-8", w1.Header().Get("Content-Type"))
|
||||
|
||||
w2 := httptest.NewRecorder()
|
||||
datas := []map[string]interface{}{{
|
||||
"foo": "bar",
|
||||
}, {
|
||||
"bar": "foo",
|
||||
}}
|
||||
|
||||
err2 := (SecureJSON{"while(1);", datas}).Render(w2)
|
||||
assert.NoError(t, err2)
|
||||
assert.Equal(t, "while(1);[{\"foo\":\"bar\"},{\"bar\":\"foo\"}]", w2.Body.String())
|
||||
assert.Equal(t, "application/json; charset=utf-8", w2.Header().Get("Content-Type"))
|
||||
}
|
||||
|
||||
type xmlmap map[string]interface{}
|
||||
|
||||
// Allows type H to be used with xml.Marshal
|
||||
|
Reference in New Issue
Block a user