-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
62 lines (58 loc) · 1.45 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
package slot
import (
"net/http"
"golang.org/x/sync/errgroup"
)
func Chain(handlers ...http.Handler) http.Handler {
if len(handlers) == 1 {
return handlers[0]
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pipeline := newPipeline(w)
for i := 0; i < len(handlers); i++ {
handler := handlers[i]
r := r.Clone(r.Context())
r.Body = pipeline
handler.ServeHTTP(pipeline, r)
pipeline.Close()
pipeline = pipeline.Next()
}
state, err := readState(pipeline)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write([]byte(state.Data))
})
}
func Batch(handlers ...http.Handler) http.Handler {
if len(handlers) == 1 {
return handlers[0]
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pipeline := newPipeline(w)
eg, ctx := errgroup.WithContext(r.Context())
for i := 0; i < len(handlers); i++ {
handler := handlers[i]
innerPipeline := pipeline
r := r.Clone(ctx)
r.Body = innerPipeline
eg.Go(func() (err error) {
defer func() { err = innerPipeline.Close() }()
handler.ServeHTTP(innerPipeline, r)
return err
})
pipeline = pipeline.Next()
}
if err := eg.Wait(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
state, err := readState(pipeline)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write([]byte(state.Data))
})
}