forked from ignite/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpstatuschecker.go
50 lines (44 loc) · 1.05 KB
/
httpstatuschecker.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
// httpstatuschecker is a tool check health of http pages.
package httpstatuschecker
import (
"context"
"net/http"
)
type checker struct {
c *http.Client
addr string
method string
}
// Option used to customize checker.
type Option func(*checker)
// Method configures http method.
func Method(name string) Option {
return func(cr *checker) {
cr.method = name
}
}
// Check checks if given http addr is alive by applying options.
func Check(ctx context.Context, addr string, options ...Option) (isAvailable bool, err error) {
cr := &checker{
c: http.DefaultClient,
addr: addr,
method: http.MethodGet,
}
for _, o := range options {
o(cr)
}
return cr.check(ctx)
}
func (c *checker) check(ctx context.Context) (bool, error) {
req, err := http.NewRequestWithContext(ctx, c.method, c.addr, nil)
if err != nil {
return false, err
}
res, err := c.c.Do(req)
if err != nil {
return false, nil
}
defer res.Body.Close()
isOKStatus := res.StatusCode >= http.StatusOK && res.StatusCode < http.StatusMultipleChoices
return isOKStatus, nil
}