...
1
2
3
4
5
6 package ctxhttp
7
8 import (
9 "context"
10 "io"
11 "net/http"
12 "net/url"
13 "strings"
14 )
15
16
17
18
19
20
21
22
23 func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
24 if client == nil {
25 client = http.DefaultClient
26 }
27 resp, err := client.Do(req.WithContext(ctx))
28
29
30 if err != nil {
31 select {
32 case <-ctx.Done():
33 err = ctx.Err()
34 default:
35 }
36 }
37 return resp, err
38 }
39
40
41 func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
42 req, err := http.NewRequest("GET", url, nil)
43 if err != nil {
44 return nil, err
45 }
46 return Do(ctx, client, req)
47 }
48
49
50 func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
51 req, err := http.NewRequest("HEAD", url, nil)
52 if err != nil {
53 return nil, err
54 }
55 return Do(ctx, client, req)
56 }
57
58
59 func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) {
60 req, err := http.NewRequest("POST", url, body)
61 if err != nil {
62 return nil, err
63 }
64 req.Header.Set("Content-Type", bodyType)
65 return Do(ctx, client, req)
66 }
67
68
69 func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) {
70 return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
71 }
72
View as plain text