-
Notifications
You must be signed in to change notification settings - Fork 10
/
postFormValidator.go
63 lines (53 loc) · 1.74 KB
/
postFormValidator.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
package middleware
import (
"net/http"
"github.com/RohitAwate/OAuth2Bin/oauth2/utils"
)
// PostFormValidator verifies if a request has method POST and content-type
// "application/x-www-form-urlencoded". This is turned into a middleware since
// it is a common task in OA2B.
//
// VisualError: boolean which determines whether to present a visual (HTML)
// or textual (JSON) error in case the request doesn't satisfy the above conditions
type PostFormValidator struct {
VisualError bool
}
// NewPostFormValidator returns a new instance of PostFormValidator
func NewPostFormValidator(visualError bool) PostFormValidator {
return PostFormValidator{VisualError: visualError}
}
// Handle implements the Middleware interface
// and performs the above mentioned job
func (pfv PostFormValidator) Handle(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
title := "Method Not Allowed"
desc := r.Method + " not allowed"
pfv.presentError(w, r, http.StatusMethodNotAllowed, title, desc)
return
}
contentType := r.Header.Get("Content-Type")
if contentType != "application/x-www-form-urlencoded" {
title := "Bad Request"
var desc string
if contentType == "" {
desc = "Expecting content type"
} else {
desc = "Content type not allowed: " + contentType
}
pfv.presentError(w, r, http.StatusBadRequest, title, desc)
return
}
handler.ServeHTTP(w, r)
}
}
func (pfv PostFormValidator) presentError(w http.ResponseWriter, r *http.Request, status int, title, desc string) {
if pfv.VisualError {
utils.ShowError(w, r, status, title, desc)
} else {
utils.ShowJSONError(w, r, status, utils.RequestError{
Error: title,
Desc: desc,
})
}
}