2017-11-11 04:44:02 +00:00
|
|
|
package parse
|
2017-10-16 02:23:15 +00:00
|
|
|
|
|
|
|
import (
|
2017-11-11 04:44:02 +00:00
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
2017-10-16 02:23:15 +00:00
|
|
|
"io"
|
2017-11-11 04:44:02 +00:00
|
|
|
"net/http"
|
|
|
|
|
2017-10-16 02:23:15 +00:00
|
|
|
"github.com/rancher/norman/httperror"
|
|
|
|
)
|
|
|
|
|
2017-11-11 04:44:02 +00:00
|
|
|
const reqMaxSize = (2 * 1 << 20) + 1
|
2017-10-16 02:23:15 +00:00
|
|
|
|
|
|
|
var bodyMethods = map[string]bool{
|
2017-11-11 04:44:02 +00:00
|
|
|
http.MethodPut: true,
|
2017-10-16 02:23:15 +00:00
|
|
|
http.MethodPost: true,
|
|
|
|
}
|
|
|
|
|
2017-11-11 04:44:02 +00:00
|
|
|
func ReadBody(req *http.Request) (map[string]interface{}, error) {
|
2017-10-16 02:23:15 +00:00
|
|
|
if !bodyMethods[req.Method] {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
2018-01-20 04:29:57 +00:00
|
|
|
dec := json.NewDecoder(io.LimitReader(req.Body, reqMaxSize))
|
|
|
|
dec.UseNumber()
|
2017-10-16 02:23:15 +00:00
|
|
|
|
|
|
|
data := map[string]interface{}{}
|
2018-01-20 04:29:57 +00:00
|
|
|
if err := dec.Decode(&data); err != nil {
|
2017-11-21 20:46:30 +00:00
|
|
|
return nil, httperror.NewAPIError(httperror.InvalidBodyContent,
|
2017-10-16 02:23:15 +00:00
|
|
|
fmt.Sprintf("Failed to parse body: %v", err))
|
|
|
|
}
|
|
|
|
|
|
|
|
return data, nil
|
|
|
|
}
|