-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoption.go
41 lines (32 loc) · 1.06 KB
/
option.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
package qst
import (
"net/http"
)
// Option is an option for building an *http.Request.
type Option interface {
Apply(request *http.Request) (*http.Request, error)
}
// Pipeline is a collection of options, which can be applied as a whole.
type Pipeline []Option
// Apply applies the Pipeline to the *http.Request.
func (p Pipeline) Apply(request *http.Request) (*http.Request, error) {
for _, option := range p {
var err error
request, err = option.Apply(request.Clone(request.Context()))
if err != nil {
return nil, err
}
}
return request, nil
}
func (p Pipeline) With(options ...Option) Pipeline {
return append(p, options...)
}
// OptionFunc is a function form of Option.
type OptionFunc func(request *http.Request) (*http.Request, error)
// Apply applies the OptionFunc to the *http.Request.
func (f OptionFunc) Apply(request *http.Request) (*http.Request, error) { return f(request) }
// Apply applies the Options to the *http.Request.
func Apply(request *http.Request, options ...Option) (*http.Request, error) {
return Pipeline(options).Apply(request)
}