1
0
mirror of https://github.com/rancher/steve.git synced 2025-09-08 18:59:58 +00:00
This commit is contained in:
Darren Shepherd
2020-01-30 22:37:59 -07:00
parent 19c6732de0
commit 8b42d0aff8
71 changed files with 4024 additions and 507 deletions

View File

@@ -0,0 +1,56 @@
package parse
import (
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/rancher/steve/pkg/schemaserver/httperror"
"github.com/rancher/steve/pkg/schemaserver/types"
"github.com/rancher/wrangler/pkg/data/convert"
"github.com/rancher/wrangler/pkg/schemas/validation"
"k8s.io/apimachinery/pkg/util/yaml"
)
const reqMaxSize = (2 * 1 << 20) + 1
var bodyMethods = map[string]bool{
http.MethodPut: true,
http.MethodPost: true,
}
type Decode func(interface{}) error
func ReadBody(req *http.Request) (types.APIObject, error) {
if !bodyMethods[req.Method] {
return types.APIObject{}, nil
}
decode := getDecoder(req, io.LimitReader(req.Body, maxFormSize))
data := map[string]interface{}{}
if err := decode(&data); err != nil {
return types.APIObject{}, httperror.NewAPIError(validation.InvalidBodyContent,
fmt.Sprintf("Failed to parse body: %v", err))
}
return toAPI(data), nil
}
func toAPI(data map[string]interface{}) types.APIObject {
return types.APIObject{
Type: convert.ToString(data["type"]),
ID: convert.ToString(data["id"]),
Object: data,
}
}
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
}