1
0
mirror of https://github.com/rancher/norman.git synced 2025-04-27 19:15:07 +00:00
norman/parse/read_input.go
Steffan Tucker 1e41884a06
Fix golangci-lint issues
As part of updating dapper files, golangci-lint was set to be used. This
caused a lot of lint issues to crop up, which this fixes.
2022-07-26 10:40:30 -06:00

44 lines
925 B
Go

package parse
import (
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/rancher/norman/httperror"
"k8s.io/apimachinery/pkg/util/yaml"
)
var bodyMethods = map[string]bool{
http.MethodPut: true,
http.MethodPost: true,
}
type Decode func(interface{}) error
func ReadBody(req *http.Request) (map[string]interface{}, error) {
if !bodyMethods[req.Method] {
return nil, nil
}
decode := getDecoder(req, io.LimitReader(req.Body, maxFormSize))
data := map[string]interface{}{}
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
}