-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
59 lines (45 loc) · 930 Bytes
/
http.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
package http
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"github.com/go-waitfor/waitfor"
)
const Scheme = "http"
type HTTP struct {
url *url.URL
}
func Use() waitfor.ResourceConfig {
return waitfor.ResourceConfig{
Scheme: []string{Scheme, Scheme + "s"},
Factory: New,
}
}
func New(u *url.URL) (waitfor.Resource, error) {
if u == nil {
return nil, fmt.Errorf("%q: %w", "url", waitfor.ErrInvalidArgument)
}
return &HTTP{u}, nil
}
func (h *HTTP) Test(ctx context.Context) error {
req, err := http.NewRequest(http.MethodGet, h.url.String(), nil)
if err != nil {
return err
}
client := http.Client{}
resp, err := client.Do(req.WithContext(ctx))
if err != nil {
return err
}
defer func() {
if resp.Body != nil {
_ = resp.Body.Close()
}
}()
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusBadRequest {
return errors.New(resp.Status)
}
return err
}