-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpclient.go
116 lines (106 loc) · 2.48 KB
/
httpclient.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package http
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/fperf/fperf"
)
type options struct {
keepalive bool
urls []string
method string
userAgent string
body string
lb string
timeout time.Duration
}
type httpClient struct {
cli http.Client
opts options
lb func() int
}
func newHTTPClient(flag *fperf.FlagSet) fperf.Client {
c := new(httpClient)
flag.BoolVar(&c.opts.keepalive, "keepalive", true, "keep connection alive")
flag.StringVar(&c.opts.method, "method", "GET", "method of HTTP request, methods:GET,POST,HEAD,OPTIONS,PUT,DELETE")
flag.StringVar(&c.opts.userAgent, "user-agent", "fperf-http-client", "customize the header User-Agent")
flag.StringVar(&c.opts.body, "body", "", "content of request body")
flag.StringVar(&c.opts.lb, "lb", "rr", "load banlancer, can be none, rr or rand")
flag.DurationVar(&c.opts.timeout, "timeout", 10*time.Second, "timeout of request")
flag.Usage = func() {
fmt.Printf("Usage: http [options] <url>\noptions:\n")
flag.PrintDefaults()
}
flag.Parse()
if len(flag.Args()) == 0 {
flag.Usage()
os.Exit(-1)
}
c.opts.urls = strings.Split(flag.Arg(0), ";")
if len(c.opts.urls) == 1 {
c.lb = loadBalancer("none", 0)
} else {
c.lb = loadBalancer(c.opts.lb, len(c.opts.urls))
}
return c
}
func (c *httpClient) Dial(addr string) error {
tr := &http.Transport{
DisableKeepAlives: !c.opts.keepalive,
}
c.cli = http.Client{
Transport: tr,
Timeout: c.opts.timeout,
}
return nil
}
func loadBalancer(method string, max int) func() int {
var m sync.Mutex
i := 0
switch method {
default:
fallthrough
case "none":
return func() int {
return 0
}
case "rr": //round robin
return func() int {
m.Lock()
v := i
i++
m.Unlock()
return v % max
}
case "rand":
return func() int { // the global rand is thread safety
return rand.Intn(max)
}
}
}
func (c httpClient) Request() error {
url := c.opts.urls[c.lb()]
req, err := http.NewRequest(c.opts.method, url, bytes.NewReader([]byte(c.opts.body)))
if err != nil {
return err
}
req.Header.Set("User-Agent", c.opts.userAgent)
resp, err := c.cli.Do(req)
if err != nil {
return err
}
// Read to EOF, then the connection could be cached(keepalive) for next use
// See details: https://serholiu.com/go-http-client-keepalive
io.Copy(ioutil.Discard, resp.Body)
return resp.Body.Close()
}
func init() {
fperf.Register("http", newHTTPClient, "HTTP performance benchmark client")
}