-
Notifications
You must be signed in to change notification settings - Fork 3
/
context.go
55 lines (47 loc) · 1.23 KB
/
context.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
package sugar
import (
"context"
"net/http"
)
// Context keeps all necessary params to build a request,
// and it allows us to pass params between plugins and encoders.
type Context struct {
ctx context.Context
Request *http.Request
Response *http.Response
Method string
RawUrl string
params []interface{}
plugins []Plugin
index int
Encoders EncoderGroup
Decoders DecoderGroup
transporter Transporter
}
// BuildRequest initializes a new request and encodes params via encoders.
func (c *Context) BuildRequest() (*http.Request, error) {
req, err := http.NewRequestWithContext(c.ctx, c.Method, c.RawUrl, nil)
if err != nil {
return nil, err
}
for i, param := range c.params {
chain := NewEncoderChain(&RequestContext{Request: req, Params: c.params, Param: param, ParamIndex: i}, c.Encoders...)
if err := chain.Next(); err != nil {
return nil, err
}
}
return req, nil
}
func (c *Context) reset() {
c.index = 0
}
// Next invokes plugins and then sends the request via *http.Client.
func (c *Context) Next() error {
if c.index < len(c.plugins) {
c.index++
return c.plugins[c.index-1].Handle(c)
}
resp, err := c.transporter.Do(c.Request)
c.Response = resp
return err
}