1
0
mirror of https://github.com/rancher/norman.git synced 2025-09-17 23:59:36 +00:00

add yaml support

This commit is contained in:
Daishan Peng
2018-05-24 10:28:05 -07:00
committed by Darren Shepherd
parent 79b91ea33c
commit 59c4a298e8
7 changed files with 80 additions and 20 deletions

View File

@@ -23,6 +23,7 @@ var (
allowedFormats = map[string]bool{
"html": true,
"json": true,
"yaml": true,
}
)
@@ -259,9 +260,17 @@ func parseResponseFormat(req *http.Request) string {
if IsBrowser(req, true) {
return "html"
}
if isYaml(req) {
return "yaml"
}
return "json"
}
func isYaml(req *http.Request) bool {
return strings.Contains(req.Header.Get("Accept"), "application/yaml")
}
func parseMethod(req *http.Request) string {
method := req.URL.Query().Get("_method")
if method == "" {

View File

@@ -7,6 +7,7 @@ import (
"net/http"
"github.com/rancher/norman/httperror"
"k8s.io/apimachinery/pkg/util/yaml"
)
const reqMaxSize = (2 * 1 << 20) + 1
@@ -16,19 +17,29 @@ var bodyMethods = map[string]bool{
http.MethodPost: true,
}
type Decode func(interface{}) error
func ReadBody(req *http.Request) (map[string]interface{}, error) {
if !bodyMethods[req.Method] {
return nil, nil
}
dec := json.NewDecoder(io.LimitReader(req.Body, reqMaxSize))
dec.UseNumber()
decode := getDecoder(req, io.LimitReader(req.Body, maxFormSize))
data := map[string]interface{}{}
if err := dec.Decode(&data); err != nil {
if err := decode(&data); err != nil {
return nil, httperror.NewAPIError(httperror.InvalidBodyContent,
fmt.Sprintf("Failed to parse body: %v", err))
}
return data, nil
}
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
}