-
Notifications
You must be signed in to change notification settings - Fork 0
/
contenttypevalidation.go
120 lines (97 loc) · 2.85 KB
/
contenttypevalidation.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package middlewares
import (
"bytes"
"encoding/json"
"fmt"
"io"
"mime"
"net/http"
"strings"
"unicode/utf8"
"go.uber.org/zap"
"github.com/dalmarcogd/test-defi/pkg/zapctx"
)
var defaultContentTypes = []string{"application/json", "text/plain"}
// NewDefaultContentTypeValidator returns a middleware that validates if the content-type header is one of the default
// content types pre-defined and if the request body is according to the content-type header.
func NewDefaultContentTypeValidator() Middleware {
return validateContentType(defaultContentTypes)
}
// NewContentTypeValidator returns a middleware that validates if the content-type header is one of the given
// content types, a comma separated string, and if the request body is according to the content-type header.
func NewContentTypeValidator(
acceptedContentTypes string,
) (Middleware, error) {
act := strings.Split(strings.ReplaceAll(acceptedContentTypes, " ", ""), ",")
cts := make([]string, 0, len(act))
for _, ct := range act {
mt, _, err := mime.ParseMediaType(ct)
if err != nil {
return nil, fmt.Errorf("invalid Content-Type %s", ct)
}
cts = append(cts, mt)
}
return validateContentType(cts), nil
}
func validateContentType(
acceptedContentTypes []string,
) Middleware {
return func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
ctx := request.Context()
if request.Body == http.NoBody {
handler.ServeHTTP(writer, request)
return
}
ct := request.Header.Get("Content-Type")
if ct == "" {
zapctx.L(ctx).Error("missing_content_type")
writer.WriteHeader(http.StatusBadRequest)
return
}
mt, _, err := mime.ParseMediaType(ct)
if err != nil {
zapctx.L(ctx).Error("invalid_content_type", zap.Error(err))
writer.WriteHeader(http.StatusBadRequest)
return
}
if !acceptedContentType(mt, acceptedContentTypes) {
zapctx.L(ctx).Error("unaccepted_content_type", zap.String("content-type", mt))
writer.WriteHeader(http.StatusUnsupportedMediaType)
return
}
if !validContentBody(request, mt) {
zapctx.L(ctx).Error("invalid_content_body")
writer.WriteHeader(http.StatusBadRequest)
return
}
handler.ServeHTTP(writer, request)
})
}
}
func acceptedContentType(mt string, acceptedContentTypes []string) bool {
for _, act := range acceptedContentTypes {
if mt == act {
return true
}
}
return false
}
func validContentBody(request *http.Request, mimeType string) bool {
rawBody, err := io.ReadAll(request.Body)
if err != nil {
return false
}
var result bool
switch mimeType {
case "text/plain":
result = utf8.Valid(rawBody)
case "application/json":
var jm json.RawMessage
result = json.Unmarshal(rawBody, &jm) == nil
default:
result = false
}
request.Body = io.NopCloser(bytes.NewBuffer(rawBody))
return result
}