mirror of
https://github.com/rancher/steve.git
synced 2025-04-27 02:51:10 +00:00
57 lines
1.3 KiB
Go
57 lines
1.3 KiB
Go
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
|
|
}
|