return ErrBodylessRequest on get method etc.
This commit is contained in:
@@ -83,8 +83,13 @@ func ParseHeader(headerValue string) map[string]string {
|
|||||||
|
|
||||||
// Parses the post request which contains json in body.
|
// Parses the post request which contains json in body.
|
||||||
func ParseJsonBody(r *http.Request, v interface{}) error {
|
func ParseJsonBody(r *http.Request, v interface{}) error {
|
||||||
var reader io.Reader
|
switch r.Method {
|
||||||
|
case http.MethodDelete, http.MethodPatch, http.MethodPost, http.MethodPut:
|
||||||
|
default:
|
||||||
|
return ErrBodylessRequest
|
||||||
|
}
|
||||||
|
|
||||||
|
var reader io.Reader
|
||||||
if withJsonBody(r) {
|
if withJsonBody(r) {
|
||||||
reader = io.LimitReader(r.Body, maxBodyLen)
|
reader = io.LimitReader(r.Body, maxBodyLen)
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -134,6 +134,26 @@ func BenchmarkParseRaw(b *testing.B) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestParseJsonBodyless(t *testing.T) {
|
||||||
|
methods := []string{
|
||||||
|
http.MethodConnect,
|
||||||
|
http.MethodGet,
|
||||||
|
http.MethodHead,
|
||||||
|
http.MethodOptions,
|
||||||
|
http.MethodTrace,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, method := range methods {
|
||||||
|
t.Run(method, func(t *testing.T) {
|
||||||
|
r, err := http.NewRequest(http.MethodGet, "http://hello.com", nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
assert.Equal(t, ErrBodylessRequest, ParseJsonBody(r, nil))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func BenchmarkParseAuto(b *testing.B) {
|
func BenchmarkParseAuto(b *testing.B) {
|
||||||
r, err := http.NewRequest(http.MethodGet, "http://hello.com/a?name=hello&age=18&percent=3.4", nil)
|
r, err := http.NewRequest(http.MethodGet, "http://hello.com/a?name=hello&age=18&percent=3.4", nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package httpx
|
package httpx
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
const (
|
const (
|
||||||
ApplicationJson = "application/json"
|
ApplicationJson = "application/json"
|
||||||
ContentEncoding = "Content-Encoding"
|
ContentEncoding = "Content-Encoding"
|
||||||
@@ -17,3 +19,5 @@ const (
|
|||||||
CodeSignatureWrongTime
|
CodeSignatureWrongTime
|
||||||
CodeSignatureInvalidToken
|
CodeSignatureInvalidToken
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var ErrBodylessRequest = errors.New("not a POST|PUT|PATCH request")
|
||||||
Reference in New Issue
Block a user