1
0
Fork 0
loadr/main.go

115 lines
3.3 KiB
Go
Raw Normal View History

2024-01-14 16:13:45 -07:00
package main
import (
2024-01-14 19:47:56 -07:00
"bytes"
2024-01-14 16:13:45 -07:00
"flag"
"fmt"
2024-01-14 19:47:56 -07:00
"io"
2024-01-14 16:13:45 -07:00
"net/http"
2024-01-14 19:47:56 -07:00
"os"
"strings"
2024-01-14 16:13:45 -07:00
"sync/atomic"
"time"
)
2024-01-14 19:47:56 -07:00
// Global HTTP client used for making requests.
2024-01-14 16:13:45 -07:00
var client = &http.Client{}
2024-01-14 19:47:56 -07:00
// makeRequest sends an HTTP request with the specified verb, URL, bearer token, and JSON data.
// It prints out the status code, response time, and response size.
func makeRequest(verb, url, token string, jsonData []byte) {
startTime := time.Now()
// Create a new request with the provided verb, URL, and JSON data if provided.
var req *http.Request
var err error
if jsonData != nil {
req, err = http.NewRequest(verb, url, bytes.NewBuffer(jsonData))
req.Header.Set("Content-Type", "application/json")
} else {
req, err = http.NewRequest(verb, url, nil)
}
if err != nil {
fmt.Println("Error creating request:", err)
return
}
// Add the bearer token to the request's Authorization header if provided.
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
// Send the request.
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error making request:", err)
return
}
defer resp.Body.Close()
// Calculate the duration of the request.
duration := time.Since(startTime)
// Read the response body to determine its size.
body, err := io.ReadAll(resp.Body)
2024-01-14 16:13:45 -07:00
if err != nil {
2024-01-14 19:47:56 -07:00
fmt.Println("Error reading response body:", err)
2024-01-14 16:13:45 -07:00
return
}
2024-01-14 19:47:56 -07:00
// Print out the request details.
fmt.Printf("Request Sent. Status Code: %d, Duration: %s, Response Size: %d bytes\n", resp.StatusCode, duration, len(body))
}
// readJSONFile reads the contents of the JSON file at the given path and returns the bytes.
func readJSONFile(filePath string) ([]byte, error) {
if filePath == "" {
return nil, nil
}
return os.ReadFile(filePath)
2024-01-14 16:13:45 -07:00
}
func main() {
2024-01-14 19:47:56 -07:00
// Define command-line flags for configuring the load test.
2024-01-14 16:13:45 -07:00
requestsPerSecond := flag.Float64("rate", 10, "Number of requests per second")
2024-01-14 19:47:56 -07:00
maxRequests := flag.Int("max", 0, "Maximum number of requests to send (0 for unlimited)")
2024-01-14 16:13:45 -07:00
url := flag.String("url", "https://example.com", "The URL to make requests to")
2024-01-14 19:47:56 -07:00
requestType := flag.String("type", "GET", "Type of HTTP request (GET, POST, PUT, DELETE, etc.)")
jsonFilePath := flag.String("json", "", "Path to the JSON file with request data")
bearerToken := flag.String("token", "", "Bearer token for authorization")
2024-01-14 16:13:45 -07:00
2024-01-14 19:47:56 -07:00
// Parse the command-line flags.
2024-01-14 16:13:45 -07:00
flag.Parse()
2024-01-14 19:47:56 -07:00
// Read the JSON file if the path is provided.
jsonData, err := readJSONFile(*jsonFilePath)
if err != nil {
fmt.Println("Error reading JSON file:", err)
return
}
// Calculate the rate limit based on the requests per second.
2024-01-14 16:13:45 -07:00
rateLimit := time.Second / time.Duration(*requestsPerSecond)
ticker := time.NewTicker(rateLimit)
defer ticker.Stop()
2024-01-14 19:47:56 -07:00
// Initialize the request count.
2024-01-14 16:13:45 -07:00
var requestCount int32 = 0
2024-01-14 19:47:56 -07:00
// Start sending requests at the specified rate.
2024-01-14 16:13:45 -07:00
for range ticker.C {
2024-01-14 19:47:56 -07:00
// Stop if the maximum number of requests is reached.
if *maxRequests > 0 && int(requestCount) >= *maxRequests {
break
}
// Send the request in a new goroutine.
go func(u, t, verb string, data []byte) {
makeRequest(verb, u, t, data)
atomic.AddInt32(&requestCount, 1)
}(*url, *bearerToken, strings.ToUpper(*requestType), jsonData)
2024-01-14 16:13:45 -07:00
}
2024-01-14 19:47:56 -07:00
// Print out the total number of requests sent after the load test is finished.
fmt.Printf("Finished sending requests. Total requests: %d\n", requestCount)
2024-01-14 16:13:45 -07:00
}