/
body.go
37 lines (29 loc) · 1.09 KB
/
body.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package middleware
// Copyright (c) Microsoft Corporation.
// Licensed under the Apache License 2.0.
import (
"context"
"io/ioutil"
"net/http"
"strings"
"github.com/Azure/ARO-RP/pkg/api"
)
func Body(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPatch, http.MethodPost, http.MethodPut:
body, err := ioutil.ReadAll(http.MaxBytesReader(w, r.Body, 1048576))
if err != nil {
api.WriteError(w, http.StatusBadRequest, api.CloudErrorCodeInvalidResource, "", "The resource definition is invalid.")
return
}
contentType := strings.SplitN(r.Header.Get("Content-Type"), ";", 2)[0]
if contentType != "application/json" && !(len(body) == 0 && contentType == "") {
api.WriteError(w, http.StatusUnsupportedMediaType, api.CloudErrorCodeUnsupportedMediaType, "", "The content media type '%s' is not supported. Only 'application/json' is supported.", r.Header.Get("Content-Type"))
return
}
r = r.WithContext(context.WithValue(r.Context(), ContextKeyBody, body))
}
h.ServeHTTP(w, r)
})
}