Created
September 20, 2019 08:35
-
-
Save na--/1d91aaa512594718fe3b085b8478cc9b to your computer and use it in GitHub Desktop.
A simple script that can hammer a given URL with configurable concurrency and number of requests.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"io" | |
"io/ioutil" | |
"log" | |
"net" | |
"net/http" | |
"sync" | |
"sync/atomic" | |
"time" | |
) | |
func hammer(url string, reqCount *int64, wg *sync.WaitGroup) { | |
defer wg.Done() | |
req, err := http.NewRequest("GET", url, nil) | |
if err != nil { | |
log.Fatal(err) | |
} | |
transport := &http.Transport{ | |
DialContext: (&net.Dialer{ | |
Timeout: 30 * time.Second, | |
KeepAlive: 30 * time.Second, | |
}).DialContext, | |
MaxIdleConns: 500, | |
IdleConnTimeout: 90 * time.Second, | |
ExpectContinueTimeout: 1 * time.Second, | |
} | |
client := http.Client{Transport: transport} | |
for { | |
remaining := atomic.AddInt64(reqCount, -1) | |
if remaining < 0 { | |
return | |
} | |
resp, err := client.Do(req) | |
if err != nil { | |
log.Println(err) | |
continue | |
} | |
if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil { | |
log.Println(err) | |
} | |
if err := resp.Body.Close(); err != nil { | |
log.Println(err) | |
} | |
} | |
} | |
func main() { | |
totalRequests := flag.Int64("reqs", 1000000, "number of requests") | |
vus := flag.Int("vus", 200, "the number of pseudo-VUs") | |
testURL := flag.String("url", "http://127.0.0.1/", "the url you want to hammer") | |
flag.Parse() | |
wg := &sync.WaitGroup{} | |
remainingReqs := *totalRequests | |
start := time.Now() | |
for i := 0; i < *vus; i++ { | |
wg.Add(1) | |
go hammer(*testURL, &remainingReqs, wg) | |
} | |
go func() { | |
for { | |
reqs := atomic.LoadInt64(&remainingReqs) | |
if reqs < 0 { | |
return | |
} | |
log.Printf("Remaining requests: %d", reqs) | |
time.Sleep(1 * time.Second) | |
} | |
}() | |
wg.Wait() | |
elapsedTime := time.Now().Sub(start) | |
reqsPerSecond := float64(*totalRequests) * float64(time.Second) / float64(elapsedTime) | |
log.Printf("Requests per second: %.02f", reqsPerSecond) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment