Created
February 29, 2024 05:22
-
-
Save c2h2/fee434c5ab99763673ef22544ef82be2 to your computer and use it in GitHub Desktop.
httpbench.go, go version of simplified ab
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" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"net/http" | |
"sync" | |
"time" | |
) | |
func main() { | |
var ( | |
numRequests int | |
testTime int | |
targetURL string | |
userAgent string | |
) | |
flag.IntVar(&numRequests, "n", 1000, "Number of requests") | |
flag.IntVar(&testTime, "t", 60, "Duration of test in seconds") | |
flag.StringVar(&targetURL, "url", "http://example.com", "Target URL") | |
flag.StringVar(&userAgent, "ua", "Mozilla/5.0 (Windows NT 6.2; rv:20.0) Gecko/20121202 Firefox/20.0", "User-Agent header value") | |
flag.Parse() | |
requestsChan := make(chan struct{}, numRequests) | |
var wg sync.WaitGroup | |
var totalData int64 | |
var totalRequests int | |
var totalDuration time.Duration | |
// Start the timer | |
//startTime := time.Now() | |
timer := time.NewTimer(time.Duration(testTime) * time.Second) | |
for i := 0; i < numRequests; i++ { | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
select { | |
case <-timer.C: | |
return | |
case requestsChan <- struct{}{}: | |
req, err := http.NewRequest("GET", targetURL, nil) | |
if err != nil { | |
fmt.Printf("Failed to create request: %v\n", err) | |
return | |
} | |
req.Header.Set("User-Agent", userAgent) | |
startTime := time.Now() | |
resp, err := http.DefaultClient.Do(req) | |
if err != nil { | |
fmt.Printf("Error making request: %v\n", err) | |
return | |
} | |
nbytes, err := io.Copy(ioutil.Discard, resp.Body) | |
if err != nil { | |
fmt.Printf("Error reading response body: %v\n", err) | |
return | |
} | |
resp.Body.Close() | |
duration := time.Since(startTime) | |
totalDuration += duration | |
totalData += nbytes | |
totalRequests++ | |
<-requestsChan | |
} | |
}() | |
} | |
wg.Wait() | |
timer.Stop() | |
if totalRequests > 0 { | |
avgTime := totalDuration / time.Duration(totalRequests) | |
fmt.Printf("Total data transferred: %d Mbytes\n", totalData/1024/1024) | |
fmt.Printf("Total requests completed: %d\n", totalRequests) | |
fmt.Printf("Average time per request: %v\n", avgTime) | |
} else { | |
fmt.Println("No requests were completed.") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment