-
Notifications
You must be signed in to change notification settings - Fork 1
/
multi_reader.go
91 lines (79 loc) · 1.76 KB
/
multi_reader.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
84
85
86
87
88
89
90
91
package gopl
import (
"bytes"
"errors"
"io"
"io/ioutil"
"reflect"
"strings"
)
//
// Author: 陈哈哈 [email protected], [email protected]
//
type MultiReader struct {
bodyLength int64
bodyRaw io.ReadCloser
bodyGetFunc func() io.Reader
}
func NewMultiReader() *MultiReader {
return &MultiReader{
bodyGetFunc: func() io.Reader {
return NoBody
},
bodyLength: int64(0),
}
}
func (slf *MultiReader) Close() error {
if nil != slf.bodyRaw {
return slf.bodyRaw.Close()
} else {
return nil
}
}
func (slf *MultiReader) GetBody() io.Reader {
return slf.bodyGetFunc()
}
func (slf *MultiReader) SetBody(body io.Reader) error {
if nil == body {
return errors.New("nil body")
}
if rc, ok := body.(io.ReadCloser); !ok && body != nil {
slf.bodyRaw = ioutil.NopCloser(body)
} else {
slf.bodyRaw = rc
}
switch value := body.(type) {
case *bytes.Buffer:
slf.bodyLength = int64(value.Len())
buf := value.Bytes()
slf.bodyGetFunc = func() io.Reader {
r := bytes.NewReader(buf)
return ioutil.NopCloser(r)
}
case *bytes.Reader:
slf.bodyLength = int64(value.Len())
snapshot := *value
slf.bodyGetFunc = func() io.Reader {
r := snapshot
return ioutil.NopCloser(&r)
}
case *strings.Reader:
slf.bodyLength = int64(value.Len())
snapshot := *value
slf.bodyGetFunc = func() io.Reader {
r := snapshot
return ioutil.NopCloser(&r)
}
default:
if nil != body {
return errors.New("unknown body reader implements: " + reflect.TypeOf(body).String())
}
}
return nil
}
////
var NoBody = noBody{}
type noBody struct{}
func (noBody) Read([]byte) (int, error) { return 0, io.EOF }
func (noBody) Close() error { return nil }
func (noBody) WriteTo(io.Writer) (int64, error) { return 0, nil }