Created
June 21, 2024 14:46
-
-
Save umtdemr/b7e106d81a4fe6d9adcd367f4982edfa to your computer and use it in GitHub Desktop.
Sends random concurrent requests to a CRUD API
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" | |
"log" | |
"math" | |
"math/rand" | |
"net/http" | |
"runtime" | |
"strings" | |
"sync" | |
"time" | |
) | |
const API_URL = "http://127.0.0.1:8080/api/" | |
var methods = []string{"GET", "PUT", "POST", "DELETE"} | |
func main() { | |
requestMethods := []string{"GET", "POST", "PUT", "DELETE"} | |
concurrentRequestCount := runtime.GOMAXPROCS(1) | |
for { | |
var wg sync.WaitGroup | |
for i := 0; i < concurrentRequestCount; i++ { | |
wg.Add(1) | |
go sendRandomRequest(&wg) | |
} | |
wg.Wait() | |
} | |
fmt.Println(requestMethods) | |
} | |
func sendRandomRequest(wg *sync.WaitGroup) { | |
defer wg.Done() | |
randomIdx := int(math.Floor(rand.Float64() * 4)) | |
randomMethod := methods[randomIdx] | |
requestUrl := fmt.Sprintf("%s%s", API_URL, strings.ToLower(randomMethod)) | |
req, err := http.NewRequest(randomMethod, requestUrl, nil) | |
if err != nil { | |
log.Fatal("err", err) | |
} | |
client := http.Client{} | |
before := time.Now() | |
resp, err := client.Do(req) | |
if err != nil { | |
log.Fatal("err2", err) | |
} | |
duration := time.Since(before) | |
defer resp.Body.Close() | |
fmt.Printf("%s - %vms\n", randomMethod, duration.Milliseconds()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment