-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchains.go
83 lines (68 loc) · 1.62 KB
/
chains.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
78
79
80
81
82
83
package iodb
import (
"io"
"github.com/alpineiq/iodb/mw"
"go.oneofone.dev/oerrs"
)
// MiddlewareError represents an error that happened in a middleware
type MiddlewareError struct {
Mw mw.Middleware
Err error
}
func (wr *MiddlewareError) Error() string {
return wr.Mw.Name() + ": " + wr.Err.Error()
}
type writerChain []io.WriteCloser
func (wc writerChain) Write(p []byte) (int, error) {
return wc[len(wc)-1].Write(p)
}
func (wc writerChain) Close() error {
var errl oerrs.ErrorList
for i := len(wc) - 1; i >= 0; i-- {
errl.PushIf(wc[i].Close())
}
return errl.Err()
}
type readerChain []io.ReadCloser
func (rc readerChain) Read(p []byte) (int, error) {
return rc[len(rc)-1].Read(p)
}
func (rc readerChain) Close() error {
var errl oerrs.ErrorList
for i := len(rc) - 1; i >= 0; i-- {
errl.PushIf(rc[i].Close())
}
return errl.Err()
}
type middlewareList []mw.Middleware
func (mwl middlewareList) applyWriters(path string, w io.WriteCloser) (io.WriteCloser, error) {
wc := make(writerChain, 0, len(mwl)+1)
wc = append(wc, w)
for _, mw := range mwl {
mww, err := mw.Writer(path, w)
if err != nil {
wc.Close()
return nil, &MiddlewareError{mw, err}
}
w = mww
wc = append(wc, w)
}
return wc, nil
}
func (mwl middlewareList) applyReaders(path string, rd *Reader) (io.ReadCloser, error) {
var (
r io.ReadCloser = rd
rc = append(make(readerChain, 0, len(mwl)+1), rd)
st = rd.Stat()
)
for _, mw := range mwl {
mwr, err := mw.Reader(path, r, st)
if err != nil {
rc.Close()
return nil, &MiddlewareError{mw, err}
}
r = mwr
rc = append(rc, r)
}
return rc, nil
}