-
Notifications
You must be signed in to change notification settings - Fork 8
/
requests.go
58 lines (50 loc) · 1.49 KB
/
requests.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
package rata
import (
"fmt"
"io"
"net/http"
)
// RequestGenerator creates http.Request objects with the correct path and method
// pre-filled for the given route object. You can also set the the host and,
// optionally, any headers you would like included with every request.
type RequestGenerator struct {
Header http.Header
host string
routes Routes
}
// NewRequestGenerator creates a RequestGenerator for a given host and route set.
// Host is of the form "http://example.com".
func NewRequestGenerator(host string, routes Routes) *RequestGenerator {
return &RequestGenerator{
Header: make(http.Header),
host: host,
routes: routes,
}
}
// CreateRequest creates a new http Request for the matching handler. If the
// request cannot be created, either because the handler does not exist or because
// the given params do not match the params the route requires, then CreateRequest
// returns an error.
func (r *RequestGenerator) CreateRequest(
name string,
params Params,
body io.Reader,
) (*http.Request, error) {
route, ok := r.routes.FindRouteByName(name)
if !ok {
return &http.Request{}, fmt.Errorf("No route exists with the name %s", name)
}
u, err := route.createURL(r.host, params)
if err != nil {
return &http.Request{}, err
}
req, err := http.NewRequest(route.Method, u.String(), body)
if err != nil {
return &http.Request{}, err
}
for key, values := range r.Header {
req.Header[key] = make([]string, len(values))
copy(req.Header[key], values)
}
return req, nil
}