mirror of
https://github.com/rancher/norman.git
synced 2025-09-16 15:21:33 +00:00
More initial dev
This commit is contained in:
38
parse/read_input.go
Normal file
38
parse/read_input.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package parse
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
|
||||
"github.com/rancher/norman/httperror"
|
||||
)
|
||||
|
||||
const reqMaxSize = (2 * 1 << 20) + 1
|
||||
|
||||
var bodyMethods = map[string]bool{
|
||||
http.MethodPut: true,
|
||||
http.MethodPost: true,
|
||||
}
|
||||
|
||||
func ReadBody(req *http.Request) (map[string]interface{}, error) {
|
||||
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{}{}
|
||||
if err := json.Unmarshal(content, &data); err != nil {
|
||||
return nil, httperror.NewAPIError(httperror.INVALID_BODY_CONTENT,
|
||||
fmt.Sprintf("Failed to parse body: %v", err))
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
Reference in New Issue
Block a user