Created
August 23, 2023 08:52
-
-
Save samaita/ce641ca009361a5b42f5237f6a03769f to your computer and use it in GitHub Desktop.
Load Test with Go
This file contains hidden or 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 ( | |
"fmt" | |
"net/http" | |
"sync" | |
"time" | |
) | |
const ( | |
batch = "&batch=X1" | |
baseURL = "http://localhost:8000/" + batch | |
concurrency = 50 // You can adjust the concurrency value | |
totalRequests = 5000 // Total number of requests to make | |
authToken = "Bearer <bearer>" | |
) | |
func worker(requestNum int, client *http.Client, wg *sync.WaitGroup, ch chan struct{}) { | |
defer wg.Done() | |
url := fmt.Sprintf("%s&X-Request-Number=%d", baseURL, requestNum) | |
req, err := http.NewRequest("GET", url, nil) | |
if err != nil { | |
fmt.Printf("Request %d: Error creating request: %v\n", requestNum, err) | |
return | |
} | |
req.Header.Set("Authorization", authToken) | |
resp, err := client.Do(req) | |
if err != nil { | |
fmt.Printf("Request %d: Error sending request: %v\n", requestNum, err) | |
return | |
} | |
defer resp.Body.Close() | |
fmt.Printf("Request %d: Status Code: %d\n", requestNum, resp.StatusCode) | |
// Release channel to allow another worker to start | |
<-ch | |
} | |
func main() { | |
client := &http.Client{} | |
var wg sync.WaitGroup | |
startTime := time.Now() | |
// Create a buffered channel with concurrency as its capacity | |
ch := make(chan struct{}, concurrency) | |
for i := 1; i <= totalRequests; i++ { | |
wg.Add(1) | |
ch <- struct{}{} // Acquire a slot in the channel | |
go worker(i, client, &wg, ch) | |
} | |
wg.Wait() // Wait for all requests to complete | |
elapsedTime := time.Since(startTime) | |
fmt.Printf("Total time taken: %s\n", elapsedTime) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment