- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrhandler.go
More file actions
Latest commit
52 lines (44 loc) · 1.49 KB
/
Copy patherrhandler.go
File metadata and controls
52 lines (44 loc) · 1.49 KB
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
package errhandler
import (
"encoding/json"
"net/http"
"go.yaml.in/yaml/v4"
)
// Wrap an http.HandlerFunc, allowing for errors to be handled in a more
// familiar way inside your handlers.
typeWrapfunc(w http.ResponseWriter, r*http.Request) error
// ServeHTTP is invoked when the HTTP handler is called, capturing and returning
// any errors encountered in the ErrHandlerFunc.
func (fnWrap) ServeHTTP(w http.ResponseWriter, r*http.Request) {
iferr:=fn(w, r); err!=nil {
ifcerr, ok:=err.(HTTPError); ok {
http.Error(w, cerr.Error(), cerr.status)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
// SendJSON returns a JSON response to the caller, or fails with an error.
funcSendJSON(w http.ResponseWriter, dataany) error {
w.Header().Set("Content-Type", "application/json")
iferr:=json.NewEncoder(w).Encode(data); err!=nil {
returnerr
}
returnnil
}
// SendString returns a string response to the caller, or fails with an error.
funcSendString(w http.ResponseWriter, messagestring) error {
w.Header().Set("Content-Type", "text/plain")
if_, err:=w.Write([]byte(message)); err!=nil {
returnerr
}
returnnil
}
// ParseJSON can be used to parse a string from the body of a request.
funcParseJSON(r*http.Request, valany) error {
returnjson.NewDecoder(r.Body).Decode(val)
}
// ParseYAML can be used to parse a string from the body of a request.
funcParseYAML(r*http.Request, valany) error {
returnyaml.NewDecoder(r.Body).Decode(val)
}