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
|
|
|
"io/ioutil"
|
|
|
|
"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
|
|
|
|
}
|
|
|
|
|
|
|
|
content, err := ioutil.ReadAll(io.LimitReader(req.Body, reqMaxSize))
|
|
|
|
if err != nil {
|
|
|
|
return nil, httperror.NewAPIError(httperror.INVALID_BODY_CONTENT,
|
|
|
|
fmt.Sprintf("Body content longer than %d bytes", reqMaxSize-1))
|
|
|
|
}
|
|
|
|
|
|
|
|
data := map[string]interface{}{}
|
2017-11-11 04:44:02 +00:00
|
|
|
if err := json.Unmarshal(content, &data); err != nil {
|
2017-10-16 02:23:15 +00:00
|
|
|
return nil, httperror.NewAPIError(httperror.INVALID_BODY_CONTENT,
|
|
|
|
fmt.Sprintf("Failed to parse body: %v", err))
|
|
|
|
}
|
|
|
|
|
|
|
|
return data, nil
|
|
|
|
}
|