1
0
mirror of https://github.com/rancher/norman.git synced 2025-04-28 11:24:47 +00:00
norman/parse/read_input.go

44 lines
925 B
Go
Raw Permalink Normal View History

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"
2018-05-24 17:28:05 +00:00
"k8s.io/apimachinery/pkg/util/yaml"
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,
}
2018-05-24 17:28:05 +00:00
type Decode func(interface{}) error
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-05-24 17:28:05 +00:00
decode := getDecoder(req, io.LimitReader(req.Body, maxFormSize))
2017-10-16 02:23:15 +00:00
data := map[string]interface{}{}
2018-05-24 17:28:05 +00:00
if err := 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
}
2018-05-24 17:28:05 +00:00
func getDecoder(req *http.Request, reader io.Reader) Decode {
if req.Header.Get("Content-type") == "application/yaml" {
return yaml.NewYAMLToJSONDecoder(reader).Decode
}
decoder := json.NewDecoder(reader)
decoder.UseNumber()
return decoder.Decode
}