/
multiplexer.go
60 lines (50 loc) · 1.73 KB
/
multiplexer.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
package multiplexer
import (
"errors"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
"net/http"
)
var (
// ErrNoHandlerFulfilled is returned if no provided handler can fulfill a request
// accepted by the server. These errors can be avoided using default handlers such
// as the HTTP HTTPHandler, which automatically fulfills all requests
ErrNoHandlerFulfilled = errors.New("no handler was fulfilled for your request")
)
// HandlerFactory is a function that implements wrapping a given http handler
// into a specific Handler
type HandlerFactory func(server http.Handler, selectors ...Selector) Handler
// Handler is a http.Handler that returns true/false based on if the
// request is being fulfilled by the handler or not
type Handler func(http.ResponseWriter, *http.Request) bool
// Selector is a function that returns true if the request should be
// handled by the Handler is corresponds to
type Selector func(*http.Request) bool
// OrSelector returns true if one of the selects is fulfilled
func OrSelector(selectors ...Selector) Selector {
return func(r *http.Request) bool {
for _, s := range selectors {
if s(r) {
return true
}
}
return false
}
}
// Make creates a new multiplexer with given handlers. It combines all handlers
// to create a new h2c handler. If the server is not provided, a default http2 server
// will be created instead.
func Make(server *http2.Server, handlers ...Handler) http.Handler {
if server == nil {
server = &http2.Server{}
}
return h2c.NewHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for _, h := range handlers {
if h(w, r) {
return
}
}
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(ErrNoHandlerFulfilled.Error()))
}), server)
}