Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Interrupt sending requests when Ctrl+C is received #267

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion hey.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package main

import (
"context"
"flag"
"fmt"
"io/ioutil"
Expand Down Expand Up @@ -191,7 +192,10 @@ func main() {
}
}

req, err := http.NewRequest(method, url, nil)
parentCtx, parentCtxCancel := context.WithCancel(context.Background())
defer parentCtxCancel()

req, err := http.NewRequestWithContext(parentCtx, method, url, nil)
if err != nil {
usageAndExit(err.Error())
}
Expand Down Expand Up @@ -241,11 +245,13 @@ func main() {
signal.Notify(c, os.Interrupt)
go func() {
<-c
parentCtxCancel()
w.Stop()
}()
if dur > 0 {
go func() {
time.Sleep(dur)
parentCtxCancel()
w.Stop()
}()
}
Expand Down
15 changes: 2 additions & 13 deletions requester/requester.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,6 @@ type Work struct {

RequestBody []byte

// RequestFunc is a function to generate requests. If it is nil, then
// Request and RequestData are cloned for each request.
RequestFunc func() *http.Request

// N is the total number of requests to make.
N int

Expand Down Expand Up @@ -150,12 +146,7 @@ func (b *Work) makeRequest(c *http.Client) {
var code int
var dnsStart, connStart, resStart, reqStart, delayStart time.Duration
var dnsDuration, connDuration, resDuration, reqDuration, delayDuration time.Duration
var req *http.Request
if b.RequestFunc != nil {
req = b.RequestFunc()
} else {
req = cloneRequest(b.Request, b.RequestBody)
}
req := cloneRequest(b.Request, b.RequestBody)
trace := &httptrace.ClientTrace{
DNSStart: func(info httptrace.DNSStartInfo) {
dnsStart = now()
Expand Down Expand Up @@ -265,9 +256,7 @@ func (b *Work) runWorkers() {
// cloneRequest returns a clone of the provided *http.Request.
// The clone is a shallow copy of the struct and its Header map.
func cloneRequest(r *http.Request, body []byte) *http.Request {
// shallow copy of the struct
r2 := new(http.Request)
*r2 = *r
r2 := r.WithContext(r.Context())
// deep copy of the Header
r2.Header = make(http.Header, len(r.Header))
for k, s := range r.Header {
Expand Down