-
Notifications
You must be signed in to change notification settings - Fork 3
/
httppipe.go
53 lines (44 loc) · 1.06 KB
/
httppipe.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
// Package httppipe contains an http.Handler that runs a series of http.Handler
// filters until one of them writes a response.
package httppipe
import (
"net/http"
)
// A Pipe is a collection of http.Handler filters to run.
type Pipe struct {
Handlers []http.Handler
Fallback http.HandlerFunc
}
// New initializes a Pipe with the given handlers.
func New(handlers... http.Handler) *Pipe {
p := &Pipe{Handlers: handlers}
p.Fallback = http.NotFound
return p
}
func (p *Pipe) SetFallback(handler http.Handler) {
p.Fallback = handler.ServeHTTP
}
// ServeHTTP satisfies the http.Handler interface.
func (p *Pipe) ServeHTTP(w http.ResponseWriter, r *http.Request) {
pipewriter := &pipeWriter{false, w}
for _, handler := range p.Handlers {
if handler == nil {
continue
}
handler.ServeHTTP(pipewriter, r)
if pipewriter.written {
return
}
}
if !pipewriter.written {
p.Fallback(w, r)
}
}
type pipeWriter struct {
written bool
http.ResponseWriter
}
func (w *pipeWriter) WriteHeader(status int) {
w.written = true
w.ResponseWriter.WriteHeader(status)
}