1
0
mirror of https://github.com/rancher/norman.git synced 2025-09-02 07:44:51 +00:00
Files
norman/parse/read_input.go

44 lines
925 B
Go
Raw Normal View History

2017-11-10 21:44:02 -07:00
package parse
2017-10-15 19:23:15 -07:00
import (
2017-11-10 21:44:02 -07:00
"encoding/json"
"fmt"
2017-10-15 19:23:15 -07:00
"io"
2017-11-10 21:44:02 -07:00
"net/http"
2017-10-15 19:23:15 -07:00
"github.com/rancher/norman/httperror"
2018-05-24 10:28:05 -07:00
"k8s.io/apimachinery/pkg/util/yaml"
2017-10-15 19:23:15 -07:00
)
var bodyMethods = map[string]bool{
2017-11-10 21:44:02 -07:00
http.MethodPut: true,
2017-10-15 19:23:15 -07:00
http.MethodPost: true,
}
2018-05-24 10:28:05 -07:00
type Decode func(interface{}) error
2017-11-10 21:44:02 -07:00
func ReadBody(req *http.Request) (map[string]interface{}, error) {
2017-10-15 19:23:15 -07:00
if !bodyMethods[req.Method] {
return nil, nil
}
2018-05-24 10:28:05 -07:00
decode := getDecoder(req, io.LimitReader(req.Body, maxFormSize))
2017-10-15 19:23:15 -07:00
data := map[string]interface{}{}
2018-05-24 10:28:05 -07:00
if err := decode(&data); err != nil {
2017-11-21 13:46:30 -07:00
return nil, httperror.NewAPIError(httperror.InvalidBodyContent,
2017-10-15 19:23:15 -07:00
fmt.Sprintf("Failed to parse body: %v", err))
}
return data, nil
}
2018-05-24 10:28:05 -07: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
}