-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
77 lines (63 loc) · 2.3 KB
/
handler.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
package xhttp
// This file defines a new request handler format that takes into account the
// existence of an execution context for each request handling goroutine.
import (
"encoding/json"
"net/http"
)
// Handler is the interface implemented by a request servicing object.
// If Handler is not also a HandlerLinker, it means that it can not call for
// further processing.
type Handler = http.Handler
// HandlerLinker is the interface of a request Handler to which we can attach
// another Handler. It enables the ServeHTTP method of the attached handler to
// be called from the ServeHTTP method of the first handler, if needed.
// The Link method returns the fully linked HandlerLinker.
type HandlerLinker interface {
ServeHTTP(w http.ResponseWriter, r *http.Request)
Link(Handler) HandlerLinker
}
// HandlerFunc defines a type of functions implementing the Handler interface.
type HandlerFunc = http.HandlerFunc
type handlerlinker struct {
handler Handler
next Handler
}
func (h handlerlinker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.handler.ServeHTTP(w, r) // NOTE if the context is changed, it needs to be reflected in r.Context()
if h.next != nil {
h.next.ServeHTTP(w, r)
}
}
func (h handlerlinker) Link(ha Handler) HandlerLinker {
h.next = ha
return h
}
// LinkableHandler is a function that tunr an Handler into a HandlerLinker suitable for further chaining.
// If the Handler happens to modify the context object, it should make sure to
// swap the *http.Request internal context for the new updated context via the
// WithContext method.
// A LinkableHandler always uses a cancelable context whose cancellation function
// can be retrieved by using the xhttp.CancelingKey.
func LinkableHandler(h Handler) HandlerLinker {
return handlerlinker{h, nil}
}
/*
Example of a HandlerLinker construct:
type Handler struct{
fieldA type A
fieldB typeB
.
.
.
next Handler // this is where the next handler will be registered by CallNext
}
The ServeHTTP method for this Handler can then call the next Handler if one has
been registered.
*/
// WriteJSON can be used to write a json encoded response
func WriteJSON(w http.ResponseWriter, data interface{}, statusCode int) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
return json.NewEncoder(w).Encode(data)
}