forked from rcrowley/go-tigertonic
/
method_not_allowed.go
74 lines (71 loc) · 1.86 KB
/
method_not_allowed.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
package tigertonic
import (
"encoding/json"
"fmt"
"log"
"net/http"
"sort"
"strings"
)
// MethodNotAllowedHandler responds 405 to every request with an Allow header
// and possibly with a JSON body.
type MethodNotAllowedHandler struct {
mux *TrieServeMux
}
func (h MethodNotAllowedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
methods := []string{"OPTIONS"}
if _, ok := h.mux.methods["GET"]; ok {
methods = append(methods, "HEAD")
}
for method, _ := range h.mux.methods {
methods = append(methods, method)
}
sort.Strings(methods)
w.Header().Set("Allow", strings.Join(methods, ", "))
if "OPTIONS" == r.Method {
if method := r.Header.Get(CORSRequestMethod); method != "" {
w.Header().Set(CORSAllowMethods, strings.Join(methods, ", "))
if cors, ok := h.mux.methods[method].(*CORSHandler); ok {
cors.HandleCORS(w, r)
}
}
if acceptJSON(r) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(map[string][]string{
"allow": methods,
}); nil != err {
log.Println(err)
}
} else {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, strings.Join(methods, ", "))
}
} else {
description := fmt.Sprintf(
"only %s are allowed",
strings.Join(methods, ", "),
)
if acceptJSON(r) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusMethodNotAllowed)
var e string
if SnakeCaseHTTPEquivErrors {
e = "method_not_allowed"
} else {
e = "tigertonic.MethodNotAllowed"
}
if err := json.NewEncoder(w).Encode(map[string]string{
"description": description,
"error": e,
}); nil != err {
log.Println(err)
}
} else {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprint(w, description)
}
}
}