### Complete Reporting Example Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/06-reporters.md A comprehensive example demonstrating how to set up an attack, collect results using vegeta.Metrics, and then generate Text, JSON, and Histogram reports to files and the console. ```go package main import ( "os" "time" vegeta "github.com/tsenart/vegeta/v12/lib" ) func main() { // Setup attack attacker := vegeta.NewAttacker() targeter := vegeta.NewStaticTargeter(vegeta.Target{ Method: "GET", URL: "http://api.example.com", }) pacer := vegeta.ConstantPacer{Freq: 100, Per: time.Second} // Collect results with histogram metrics := &vegeta.Metrics{ Histogram: &vegeta.Histogram{ Buckets: []time.Duration{ 0, 1*time.Millisecond, 10*time.Millisecond, 100*time.Millisecond, }, }, } results := attacker.Attack(targeter, pacer, 60*time.Second, "api-load") for res := range results { metrics.Add(res) } metrics.Close() // Generate reports // Text report textFile, _ := os.Create("report.txt") vegeta.NewTextReporter(metrics).Report(textFile) textFile.Close() // JSON report jsonFile, _ := os.Create("report.json") vegeta.NewJSONReporter(metrics).Report(jsonFile) jsonFile.Close() // Histogram report histFile, _ := os.Create("histogram.txt") vegeta.NewHistogramReporter(metrics.Histogram).Report(histFile) histFile.Close() // Console output vegeta.NewTextReporter(metrics).Report(os.Stdout) } ``` -------------------------------- ### SinePacer Example Usage Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/05-pacers.md Demonstrates how to configure and use SinePacer with an attacker. Sets a rate varying between 50 and 150 req/s over 10 minutes, starting at peak. ```go // Vary rate between 50 and 150 req/s over 10 minutes // Starting at peak (150 req/s) pacer := vegeta.SinePacer{ Period: 10 * time.Minute, Mean: vegeta.Rate{Freq: 100, Per: time.Second}, Amp: vegeta.Rate{Freq: 50, Per: time.Second}, StartAt: vegeta.Peak, } // Use in attack results := attacker.Attack(targeter, pacer, 30*time.Minute, "sine-wave") ``` -------------------------------- ### Complete Result Processing Example Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/04-results-metrics.md A full example demonstrating how to set up an attacker, run an attack, save results in binary format using gob encoding, collect metrics, and report them. ```go package main import ( "os" "time" vegeta "github.com/tsenart/vegeta/v12/lib" ) func main() { // Create attacker and run attack attacker := vegeta.NewAttacker() targeter := vegeta.NewStaticTargeter(vegeta.Target{ Method: "GET", URL: "http://example.com", }) pacer := vegeta.ConstantPacer{Freq: 100, Per: time.Second} results := attacker.Attack(targeter, pacer, 10*time.Second, "test") // Save results in binary format resultFile, _ := os.Create("results.bin") encoder := vegeta.NewEncoder(resultFile) var metrics vegeta.Metrics for res := range results { metrics.Add(res) encoder.Encode(res) } resultFile.Close() metrics.Close() // Report metrics report := vegeta.NewTextReporter(&metrics) report.Report(os.Stdout) } ``` -------------------------------- ### ConstantPacer Initialization Examples Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/05-pacers.md Demonstrates how to initialize a ConstantPacer for different request rates per second and per minute. Includes an example for an infinite rate and using the Rate type alias. ```go // 100 requests per second pacer := vegeta.ConstantPacer{Freq: 100, Per: time.Second} ``` ```go // 10 requests per minute pacer := vegeta.ConstantPacer{Freq: 10, Per: time.Minute} ``` ```go // 1000 requests per second (infinity) pacer := vegeta.ConstantPacer{Freq: 0, Per: time.Second} ``` ```go // Use the Rate type alias pacer := vegeta.Rate{Freq: 50, Per: time.Second} ``` -------------------------------- ### Vegeta Attack Command Example Source: https://github.com/tsenart/vegeta/blob/master/README.md This example demonstrates how to send 10 requests per second to a target URL and save the results to a file. Ensure the target URL is correctly formatted. ```bash echo "GET http://:80" | vegeta attack -rate=10/s > results.gob ``` -------------------------------- ### Example Attack with ConstantPacer Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/05-pacers.md Shows a complete example of setting up and running an attack using vegeta with a ConstantPacer to achieve a specific rate. It calculates and prints the actual achieved rate. ```go attacker := vegeta.NewAttacker() targeter := vegeta.NewStaticTargeter(vegeta.Target{ Method: "GET", URL: "http://api.example.com/data", }) pacer := vegeta.ConstantPacer{Freq: 100, Per: time.Second} results := attacker.Attack(targeter, pacer, 60*time.Second, "constant-rate") var metrics vegeta.Metrics for res := range results { metrics.Add(res) } metrics.Close() fmt.Printf("Actual rate: %.2f req/s\n", metrics.Rate) ``` -------------------------------- ### LinearPacer Examples Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/05-pacers.md Illustrates different configurations for LinearPacer, including ramping up, slow ramp-ups, and ramp-downs. ```go // Ramp from 10 req/s to 1000 req/s over 100 seconds // Slope = (1000-10)/100 = 9.9 req/s per second pacer := vegeta.LinearPacer{ StartAt: vegeta.Rate{Freq: 10, Per: time.Second}, Slope: 9.9, } ``` ```go // Slow ramp up: 100 to 200 req/s over 10 minutes pacer := vegeta.LinearPacer{ StartAt: vegeta.Rate{Freq: 100, Per: time.Second}, Slope: 0.0167, // 100 req/s additional per 10 minutes } ``` ```go // Ramp down (negative slope) pacer := vegeta.LinearPacer{ StartAt: vegeta.Rate{Freq: 500, Per: time.Second}, Slope: -5, // Decrease by 5 req/s per second } ``` -------------------------------- ### Install Vegeta with Pkg Source: https://github.com/tsenart/vegeta/blob/master/README.md Installs Vegeta on FreeBSD using the built-in pkg package manager. ```shell pkg install vegeta ``` -------------------------------- ### Vegeta Report Command Example Source: https://github.com/tsenart/vegeta/blob/master/README.md This example shows how to generate a text-based report from attack results stored in files matching the pattern 'results.*'. The report provides a summary of the attack performance. ```bash vegeta report results.* ``` -------------------------------- ### Text Reporter Usage Example Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/06-reporters.md Demonstrates how to collect metrics, create a Text Reporter, and then use it to report the metrics to standard output. ```go var metrics vegeta.Metrics for res := range attacker.Attack(...) { metrics.Add(res) } metrics.Close() reporter := vegeta.NewTextReporter(&metrics) reporter.Report(os.Stdout) ``` -------------------------------- ### Decode Results with Auto-Detection Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/04-results-metrics.md Example of opening a file, using DecoderFor to get the appropriate decoder, and then decoding results into metrics. ```go file, _ := os.Open("results.bin") defer file.Close() decoder := vegeta.DecoderFor(file) if decoder == nil { log.Fatal("Unknown encoding") } var metrics vegeta.Metrics var result vegeta.Result for { if err := decoder.Decode(&result); err == io.EOF { break } metrics.Add(&result) } metrics.Close() ``` -------------------------------- ### Configure Sine Pacer for Wave Pattern Load Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/00-index.md This example demonstrates the use of a SinePacer to create a wave-like load pattern, suitable for spike testing. It configures the period, mean rate, amplitude, and starting point of the sine wave. ```go pacer := vegeta.SinePacer{ Period: 10 * time.Minute, Mean: vegeta.Rate{Freq: 500, Per: time.Second}, Amp: vegeta.Rate{Freq: 300, Per: time.Second}, StartAt: vegeta.Peak, } ``` -------------------------------- ### Example ConstantPacer Initialization Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/02-types.md Shows how to initialize a ConstantPacer for different request rates. Use this to set up a fixed request frequency, such as 100 requests per second or 10 requests per minute. ```go // 100 requests per second pacer := vegeta.ConstantPacer{Freq: 100, Per: time.Second} // 10 requests per minute pacer := vegeta.ConstantPacer{Freq: 10, Per: time.Minute} ``` -------------------------------- ### Install Vegeta with Homebrew Source: https://github.com/tsenart/vegeta/blob/master/README.md Installs Vegeta on macOS using the Homebrew package manager. Ensure Homebrew is updated before installation. ```shell brew update && brew install vegeta ``` -------------------------------- ### Install Vegeta with Pacman Source: https://github.com/tsenart/vegeta/blob/master/README.md Installs Vegeta on Arch Linux using the pacman package manager. ```shell pacman -S vegeta ``` -------------------------------- ### Vegeta Attacker with Default Timeout Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/08-errors-constants.md Demonstrates how to initialize a Vegeta attacker using the default request timeout. This is the simplest way to start. ```go import vegeta "github.com/tsenart/vegeta/v12/lib" // Use default timeout attacker := vegeta.NewAttacker() ``` -------------------------------- ### Install Vegeta with MacPorts Source: https://github.com/tsenart/vegeta/blob/master/README.md Installs Vegeta on macOS using the MacPorts package manager. ```shell port install vegeta ``` -------------------------------- ### Complete Vegeta Load Testing Workflow Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/09-quick-start.md This comprehensive example demonstrates setting up an attacker, defining targets, pacing requests, running the attack, collecting results, and generating various reports (text, JSON, histogram, HTML plot). ```go package main import ( "fmt" "os" "time" vegeta "github.com/tsenart/vegeta/v12/lib" "github.com/tsenart/vegeta/v12/lib/plot" ) func main() { // 1. Setup attacker := vegeta.NewAttacker( vegeta.Workers(50), vegeta.Timeout(10*time.Second), ) targeter := vegeta.NewStaticTargeter( vegeta.Target{ Method: "GET", URL: "http://localhost:8080/api/status", }, ) pacer := vegeta.ConstantPacer{Freq: 100, Per: time.Second} // 2. Run attack fmt.Println("Starting attack...") results := attacker.Attack(targeter, pacer, 60*time.Second, "api-test") // 3. Collect results resultFile, _ := os.Create("results.bin") encoder := vegeta.NewEncoder(resultFile) metrics := &vegeta.Metrics{ Histogram: &vegeta.Histogram{ Buckets: []time.Duration{0, 1*time.Millisecond, 10*time.Millisecond, 100*time.Millisecond}, }, } p := plot.NewPlot(plot.Title("API Load Test")) for res := range results { metrics.Add(res) encoder.Encode(res) p.Add(res) } resultFile.Close() metrics.Close() // 4. Generate reports fmt.Println("\n=== Text Report ===") vegeta.NewTextReporter(metrics).Report(os.Stdout) // JSON report jsonFile, _ := os.Create("metrics.json") vegeta.NewJSONReporter(metrics).Report(jsonFile) jsonFile.Close() // Histogram fmt.Println("\n=== Histogram ===") vegeta.NewHistogramReporter(metrics.Histogram).Report(os.Stdout) // Plot htmlFile, _ := os.Create("plot.html") p.WriteTo(htmlFile) htmlFile.Close() fmt.Println("\n=== Outputs ===") fmt.Println(" Binary results: results.bin") fmt.Println(" JSON metrics: metrics.json") fmt.Println(" HTML plot: plot.html") } ``` -------------------------------- ### Complete Vegeta Visualization Example (Go) Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/07-plot-prom.md Demonstrates a complete load test using the Vegeta library in Go, including setting up the attacker, targets, pacer, running the attack, creating a custom plot with a labeler, and reporting results to both an HTML file and standard output. ```go package main import ( "fmt" "os" "time" vegeta "github.com/tsenart/vegeta/v12/lib" "github.com/tsenart/vegeta/v12/lib/plot" ) func main() { // Setup attack attacker := vegeta.NewAttacker( vegeta.Workers(20), vegeta.Timeout(10*time.Second), ) targets := []vegeta.Target{ {Method: "GET", URL: "http://api.example.com/users"}, {Method: "GET", URL: "http://api.example.com/posts"}, {Method: "GET", URL: "http://api.example.com/comments"}, } targeter := vegeta.NewStaticTargeter(targets...) pacer := vegeta.ConstantPacer{Freq: 100, Per: time.Second} // Run attack and collect results results := attacker.Attack(targeter, pacer, 30*time.Second, "api-test") // Create plot with custom labeler endpointLabeler := func(r *vegeta.Result) string { // Extract endpoint from URL if r.Code < 400 { return "Success (2xx/3xx)" } else if r.Code < 500 { return "Client Error (4xx)" } else { return "Server Error (5xx)" } } p := plot.NewPlot( plot.Title("API Endpoint Load Test - 100 req/s"), plot.Threshold(2000), plot.Labeler(endpointLabeler), ) // Collect metrics and add to plot metrics := &vegeta.Metrics{} for res := range results { metrics.Add(res) p.Add(res) } metrics.Close() // Write HTML plot plotFile, _ := os.Create("load_test.html") p.WriteTo(plotFile) plotFile.Close() // Write text report vegeta.NewTextReporter(metrics).Report(os.Stdout) fmt.Println("\nResults:") fmt.Printf(" Plot saved to: load_test.html\n") fmt.Printf(" Success rate: %.2f%%\n", metrics.Success*100) fmt.Printf(" P99 latency: %v\n", metrics.Latencies.P99) } ``` -------------------------------- ### Use Round-Robin Decoder for Mixed Formats Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/04-results-metrics.md Example of creating a round-robin decoder that first tries to decode as JSON, then as CSV, from the same file handle. ```go decoder := vegeta.NewRoundRobinDecoder( vegeta.NewJSONDecoder(file), vegeta.NewCSVDecoder(file), ) ``` -------------------------------- ### Complete Vegeta Targeting Workflow Example Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/03-targets.md Demonstrates a full Vegeta attack workflow, including defining static targets, configuring the attacker with workers and timeout, setting a request rate using a pacer, running the attack, collecting metrics, and reporting the results. ```go package main import ( "fmt" "io" "os" "strings" "time" vegeta "github.com/tsenart/vegeta/v12/lib" ) func main() { // Static targets targeter := vegeta.NewStaticTargeter( vegeta.Target{ Method: "GET", URL: "http://api.example.com/health", }, ) // Configure attacker attacker := vegeta.NewAttacker( vegeta.Workers(10), vegeta.Timeout(10*time.Second), ) // Configure rate (100 req/s) pacer := vegeta.ConstantPacer{Freq: 100, Per: time.Second} // Run attack results := attacker.Attack(targeter, pacer, 30*time.Second, "health-check") // Collect metrics var metrics vegeta.Metrics for res := range results { metrics.Add(res) } metrics.Close() // Report vegeta.NewTextReporter(&metrics).Report(os.Stdout) } ``` -------------------------------- ### Configure SinePacer with StartAt Constant Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/08-errors-constants.md Use the predefined `Peak` constant for SinePacer to start at the maximum rate. Custom offsets can be achieved by adding to constants like `MeanUp`. ```go pacer := vegeta.SinePacer{ Period: 10 * time.Minute, Mean: vegeta.Rate{Freq: 100, Per: time.Second}, Amp: vegeta.Rate{Freq: 50, Per: time.Second}, StartAt: vegeta.Peak, } ``` ```go pacer := vegeta.SinePacer{ StartAt: vegeta.MeanUp + math.Pi/4, } ``` -------------------------------- ### Start Vegeta Attack with Prometheus Exporter (CLI) Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/07-plot-prom.md Starts a Vegeta attack with the Prometheus exporter enabled on a specified address and port. Use this to expose metrics for scraping during an attack. ```bash # Start attack with Prometheus exporter on port 8880 echo "GET http://example.com" | vegeta attack \ -rate=100 \ -duration=60s \ -prometheus-addr=0.0.0.0:8880 # In another terminal, scrape metrics curl http://localhost:8880/metrics ``` -------------------------------- ### Run Vegeta Attack and Report Metrics Source: https://github.com/tsenart/vegeta/blob/master/README.md This example demonstrates a common workflow: sending HTTP requests using vegeta attack, saving the results to a binary file, and then generating a report from those results. ```console echo "GET http://localhost/" | vegeta attack -duration=5s | tee results.bin | vegeta report ``` ```console vegeta report -type=json results.bin > metrics.json ``` -------------------------------- ### Vegeta Encode and Attack Example Source: https://github.com/tsenart/vegeta/blob/master/README.md This example pipes the output of a Vegeta attack (100 requests per second) to the encode command, saving the results in JSON format. This is useful for processing attack results with other tools. ```bash echo "GET http://:80" | vegeta attack -rate=100/s | vegeta encode > results.json ``` -------------------------------- ### HTTP Target Format Example Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/00-index.md Defines the format for specifying HTTP targets, including method, URL, headers, and an optional request body file. ```text METHOD URL Header-Name: Header-Value Header-Name2: Header-Value2 [@/path/to/body/file] METHOD URL ... ``` -------------------------------- ### Rate Pattern Examples Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/MANIFEST.md Illustrates different rate patterns for attacks, including constant rate, step rate, and custom rate functions. This allows for simulating various traffic patterns. ```go package main import ( "fmt" "log" "time" vegeta "github.com/tsenart/vegeta/lib" ) func main() { target := "http://localhost:8080/" attacker := vegeta.NewAttacker() // Example 1: Constant rate rate1 := vegeta.Rate{Freq: 100, Sample: 1 * time.Minute} err := attacker.Attack(vegeta.NewTarget(target), rate1, 10*time.Second, "constant rate attack") if err != nil { log.Fatalf("Error during constant rate attack: %v", err) } fmt.Println("Constant rate attack completed.") // Example 2: Step rate (simplified representation) // Vegeta's Rate struct handles frequency, more complex step logic would require custom pacer rate2 := vegeta.Rate{Freq: 50, Sample: 1 * time.Minute} err = attacker.Attack(vegeta.NewTarget(target), rate2, 10*time.Second, "step rate attack") if err != nil { log.Fatalf("Error during step rate attack: %v", err) } fmt.Println("Step rate attack completed.") // Example 3: Custom rate (using a custom pacer function - not shown here for brevity) // Example 4: Burst rate (achieved by high frequency for short duration) rate4 := vegeta.Rate{Freq: 1000, Sample: 1 * time.Minute} err = attacker.Attack(vegeta.NewTarget(target), rate4, 5*time.Second, "burst rate attack") if err != nil { log.Fatalf("Error during burst rate attack: %v", err) } fmt.Println("Burst rate attack completed.") } ``` -------------------------------- ### Initialize Plotting Library Source: https://github.com/tsenart/vegeta/blob/master/lib/plot/testdata/TestPlot.golden.html Initializes the plotting library, sets up event listeners, and synchronizes data. This function should be called once during the setup phase. ```javascript function Li(){ Ci("init", u, g), gn(g || u.data, !1), Kl[El] ? Kn(El, Kl[El]) : xn(), wt = ei.show && (ei.width > 0 || ei.height > 0), xt = _t = !0, vt(u.width, u.height) } ``` -------------------------------- ### Decode Gob Encoded Results Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/04-results-metrics.md Example of opening a file, creating a gob decoder, and iterating through results until EOF. ```go file, _ := os.Open("results.bin") defer file.Close() decoder := vegeta.NewDecoder(file) var result vegeta.Result for { if err := decoder.Decode(&result); err == io.EOF { break } // Process result } ``` -------------------------------- ### Custom Labeler Example Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/07-plot-prom.md Demonstrates how to create and use a custom Labeler function to partition plot series by HTTP status code. The 'fmt' package is required for Sprintf. ```go // Partition by response code codeLabeler := func(r *vegeta.Result) string { return fmt.Sprintf("%d", r.Code) } plot := plot.NewPlot( plot.Labeler(codeLabeler), ) ``` -------------------------------- ### Generate Plot from Vegeta Results Source: https://github.com/tsenart/vegeta/blob/master/README.md This example shows how to take the binary results from a Vegeta test and generate an HTML plot for visualization. ```console cat results.bin | vegeta plot > plot.html ``` -------------------------------- ### Basic Attack Pattern Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/MANIFEST.md Demonstrates a simple Vegeta attack targeting a single endpoint with default settings. This is the most basic way to start load testing. ```go package main import ( "fmt" "log" vegeta "github.com/tsenart/vegeta/lib" ) func main() { target := "http://localhost:8080/" attacker := vegeta.NewAttacker() err := attacker.Attack(vegeta.NewTarget(target), vegeta.DefaultPacer, vegeta.DefaultDuration, "basic attack") if err != nil { log.Fatalf("Error during attack: %v", err) } fmt.Println("Basic attack completed.") } ``` -------------------------------- ### Configure Vegeta Attacker with Custom Options Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/00-index.md This example shows how to customize the Vegeta attacker with specific options like the number of workers, timeout duration, and keep-alive settings. This allows for fine-tuning the load generation behavior. ```go attacker := vegeta.NewAttacker( vegeta.Workers(50), vegeta.Timeout(5*time.Second), vegeta.KeepAlive(true), ) // ... rest of attack ``` -------------------------------- ### SinePacer Configuration: Gradual Increase/Decrease Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/05-pacers.md Configures a SinePacer for a gradual increase then decrease pattern over an hour, starting at the mean rate and increasing. ```go // Gradual increase then decrease (wave shape) pacer := vegeta.SinePacer{ Period: 1 * time.Hour, Mean: vegeta.Rate{Freq: 100, Per: time.Second}, Amp: vegeta.Rate{Freq: 50, Per: time.Second}, StartAt: vegeta.MeanUp, } ``` -------------------------------- ### Run Load Ramping Script Source: https://github.com/tsenart/vegeta/wiki/Load-ramping This command executes the `ramp-requests.py` script to test a target URL with increasing request rates. Ensure Vegeta, Python 3, and Gnuplot are installed. ```bash echo GET http://localhost:8080/ | python3 ramp-requests.py ``` -------------------------------- ### Configure Linear Pacer for Ramping Load Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/00-index.md This snippet illustrates how to set up a LinearPacer for a load test that ramps up from 100 to 1000 requests per second over 100 seconds. It defines the starting rate and the slope of the ramp. ```go pacer := vegeta.LinearPacer{ StartAt: vegeta.Rate{Freq: 100, Per: time.Second}, Slope: 9.0, } ``` -------------------------------- ### Collecting Results with Metrics Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/06-reporters.md Example of collecting attack results directly into a vegeta.Metrics object, which implements the Report interface. It also shows how to check for and use the Closer interface to finalize metrics. ```go report := &vegeta.Metrics{} // Implements Report interface for res := range attacker.Attack(...) { report.Add(res) // Implements Report interface } if closer, ok := report.(vegeta.Closer); ok { closer.Close() // Finalize metrics } ``` -------------------------------- ### Generate Histogram Report with Custom Buckets Source: https://github.com/tsenart/vegeta/blob/master/README.md This example demonstrates generating a histogram report from Vegeta results, specifying custom time buckets for the histogram. ```console cat results.bin | vegeta report -type="hist[0,100ms,200ms,300ms]" ``` -------------------------------- ### Generate HTML Plot from Load Test Results Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/00-index.md This example illustrates how to generate an HTML plot from load test results. It involves creating a plot object, adding results from an attacker's output, and writing the plot to an HTML file. ```go p := plot.NewPlot(plot.Title("Results")) for res := range attacker.Attack(...) { p.Add(res) } htmlFile, _ := os.Create("plot.html") p.WriteTo(htmlFile) ``` -------------------------------- ### Build Vegeta from Source Source: https://github.com/tsenart/vegeta/blob/master/README.md Clones the Vegeta repository, builds the executable using make, and optionally moves it to a directory in your PATH. ```shell git clone https://github.com/tsenart/vegeta cd vegeta make vegeta mv vegeta ~/bin # Or elsewhere, up to you. ``` -------------------------------- ### Run Simple Load Test with Vegeta Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/00-index.md This snippet demonstrates a basic load test configuration using Vegeta. It sets up a static target, a constant pacer for 100 requests per second, and runs the test for 10 seconds. Results are collected and reported to standard output as text. ```go attacker := vegeta.NewAttacker() targeter := vegeta.NewStaticTargeter(vegeta.Target{ Method: "GET", URL: "http://example.com", }) pacer := vegeta.ConstantPacer{Freq: 100, Per: time.Second} var metrics vegeta.Metrics for res := range attacker.Attack(targeter, pacer, 10*time.Second, "test") { metrics.Add(res) } metrics.Close() vegeta.NewTextReporter(&metrics).Report(os.Stdout) ``` -------------------------------- ### Configure Plot with Options Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/07-plot-prom.md Shows how to create a plot with custom configurations for title, downsampling threshold, and a labeler function. The results are then added and written to an HTML file. Ensure 'os' package is imported. ```go results := attacker.Attack(targeter, pacer, duration, "test") plot := plot.NewPlot( plot.Title("API Load Test Results"), plot.Threshold(2000), plot.Labeler(plot.ErrorLabeler), ) for res := range results { plot.Add(res) } htmlFile, _ := os.Create("results.html") plot.WriteTo(htmlFile) htmlFile.Close() ``` -------------------------------- ### Create and Use Plot Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/07-plot-prom.md Demonstrates how to create a new plot, add attack results to it, and write the generated HTML to a file. Ensure the 'os' package is imported for file operations. ```go import "github.com/tsenart/vegeta/v12/lib/plot" // Create a basic plot p := plot.NewPlot() // Add results for res := range attacker.Attack(...) { p.Add(res) } // Write HTML file, _ := os.Create("plot.html") p.WriteTo(file) file.Close() ``` -------------------------------- ### Calculate Percentile Latencies Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/04-results-metrics.md Example of calculating the 99th and 50th (median) percentile latencies from collected metrics. ```go p99 := metrics.Latencies.Quantile(0.99) p50 := metrics.Latencies.Quantile(0.50) // median ``` -------------------------------- ### HTTP Targets with Comments Source: https://github.com/tsenart/vegeta/blob/master/README.md Includes comments in HTTP target files. Lines starting with '#' are ignored by Vegeta. ```http # get a dragon ball GET http://goku:9090/path/to/dragon?item=ball # specify a test account X-Account-ID: 99 ``` -------------------------------- ### Define SinePacer Structure Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/05-pacers.md Defines the structure for SinePacer, including period, mean rate, amplitude, and starting phase. ```go type SinePacer struct { Period time.Duration Mean Rate Amp Rate StartAt float64 } ``` -------------------------------- ### SinePacer Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/02-types.md A pacer that varies the request rate sinusoidally over time, with configurable period, mean rate, amplitude, and starting offset. ```APIDOC ## SinePacer ```go type SinePacer struct { Period time.Duration Mean Rate Amp Rate StartAt float64 } ``` Pacer that varies request rate sinusoidally over time. | Field | Type | Description | |-------|------|-------------| | Period | `time.Duration` | Duration of one complete sine wave cycle | | Mean | `Rate` | Midpoint rate of the sine wave | | Amp | `Rate` | Amplitude of variation (must be < Mean) | | StartAt | `float64` | Radians offset at t=0 (MeanUp, Peak, MeanDown, Trough) | **Methods:** - `Pace(elapsed time.Duration, hits uint64) (time.Duration, bool)` - Returns wait duration - `Rate(elapsed time.Duration) float64` - Returns current rate - `String() string` - Returns formatted description **Offsets:** - `MeanUp` (0) - Start at mean, increasing - `Peak` (π/2) - Start at maximum rate - `MeanDown` (π) - Start at mean, decreasing - `Trough` (3π/2) - Start at minimum rate **Location:** `lib/pacer.go` ``` -------------------------------- ### SinePacer Configuration: Burst Pattern Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/05-pacers.md Configures a SinePacer for a burst pattern, starting at the peak rate and decreasing, over a 5-minute period. ```go // Burst pattern (start high, come down) pacer := vegeta.SinePacer{ Period: 5 * time.Minute, Mean: vegeta.Rate{Freq: 200, Per: time.Second}, Amp: vegeta.Rate{Freq: 150, Per: time.Second}, StartAt: vegeta.Peak, } ``` -------------------------------- ### Decode JSON Encoded Results Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/04-results-metrics.md Example of creating a JSON decoder from stdin and printing the status code and latency of each decoded result. ```go decoder := vegeta.NewJSONDecoder(os.Stdin) var result vegeta.Result for { if err := decoder.Decode(&result); err == io.EOF { break } fmt.Printf("Status: %d, Latency: %v\n", result.Code, result.Latency) } ``` -------------------------------- ### Configure TLS with InsecureSkipVerify Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/09-quick-start.md Set up TLS configuration to skip certificate verification, useful for testing with self-signed certificates. Use with caution in production environments. ```go tlsConfig := &tls.Config{ InsecureSkipVerify: true, } attacker := vegeta.NewAttacker( vegeta.TLSConfig(tlsConfig), ) ``` -------------------------------- ### Vegeta Library Usage for Load Testing in Go Source: https://github.com/tsenart/vegeta/blob/master/README.md Demonstrates how to use the Vegeta library in Go to perform load tests programmatically. Sets up a static targeter, attacker, and collects metrics. ```go package main import ( "fmt" "time" vegeta "github.com/tsenart/vegeta/v12/lib" ) func main() { rate := vegeta.Rate{Freq: 100, Per: time.Second} duration := 4 * time.Second targeter := vegeta.NewStaticTargeter(vegeta.Target{ Method: "GET", URL: "http://localhost:9100/", }) attacker := vegeta.NewAttacker() var metrics vegeta.Metrics for res := range attacker.Attack(targeter, rate, duration, "Big Bang!") { metrics.Add(res) } metrics.Close() fmt.Printf("99th percentile: %s\n", metrics.Latencies.P99) } ``` -------------------------------- ### Get Plot Bounds Source: https://github.com/tsenart/vegeta/blob/master/lib/plot/testdata/TestPlot.golden.html Retrieves the bounding box of a plot, likely used for positioning elements or calculating available drawing space. ```javascript function bt(l){return} ``` -------------------------------- ### Vegeta CLI Usage Manual Source: https://github.com/tsenart/vegeta/blob/master/README.md This is the main usage manual for the Vegeta command-line interface. It lists global flags and command-specific flags for attack, encode, plot, and report. ```console Usage: vegeta [global flags] [command flags] global flags: -cpus int Number of CPUs to use (default = number of cpus) -profile string Enable profiling of [cpu, heap] -version Print version and exit attack command: -body string Requests body file -cert string TLS client PEM encoded certificate file -chunked Send body with chunked transfer encoding -connect-to value A mapping of (ip|host):port to use instead of a target URL's (ip|host):port. Can be repeated multiple times. Identical src:port with different dst:port will round-robin over the different dst:port pairs. Example: google.com:80:localhost:6060 -connections int Max open idle connections per target host (default 10000) -dns-ttl value Cache DNS lookups for the given duration [-1 = disabled, 0 = forever] (default 0s) -duration duration Duration of the test [0 = forever] -format string Targets format [http, json] (default "http") -h2c Send HTTP/2 requests without TLS encryption -header value Request header -http2 Send HTTP/2 requests when supported by the server (default true) -insecure Ignore invalid server TLS certificates -keepalive Use persistent connections (default true) -key string TLS client PEM encoded private key file -laddr value Local IP address (default 0.0.0.0) -lazy Read targets lazily -max-body value Maximum number of bytes to capture from response bodies. [-1 = no limit] (default -1) -max-connections int Max connections per target host -max-workers uint Maximum number of workers (default 18446744073709551615) -name string Attack name -output string Output file (default "stdout") -prometheus-addr string Prometheus exporter listen address [empty = disabled]. Example: 0.0.0.0:8880 -proxy-header value Proxy CONNECT header -rate value Number of requests per time unit [0 = infinity] (default 50/1s) -redirects int Number of redirects to follow. -1 will not follow but marks as success (default 10) -resolvers value List of addresses (ip:port) to use for DNS resolution. Disables use of local system DNS. (comma separated list) -root-certs value TLS root certificate files (comma separated list) -session-tickets Enable TLS session resumption using session tickets -targets string Targets file (default "stdin") -timeout duration Requests timeout (default 30s) -unix-socket string Connect over a unix socket. This overrides the host address in target URLs -workers uint Initial number of workers (default 10) encode command: -output string Output file (default "stdout") -to string Output encoding [csv, gob, json] (default "json") plot command: -output string Output file (default "stdout") -threshold int Threshold of data points above which series are downsampled. (default 4000) -title string Title and header of the resulting HTML page (default "Vegeta Plot") report command: -buckets string Histogram buckets, e.g.: "[0,1ms,10ms]" -every duration Report interval -output string Output file (default "stdout") -type string Report type to generate [text, json, hist[buckets], hdrplot] (default "text") ``` -------------------------------- ### Performance Tuning - Efficient Pacing Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/MANIFEST.md Demonstrates a performance tuning pattern by optimizing the pacing of requests. Using a more efficient pacer can reduce overhead and increase throughput. ```go package main import ( "fmt" "log" "time" vegeta "github.com/tsenart/vegeta/lib" ) func main() { target := "http://localhost:8080/" attacker := vegeta.NewAttacker() // Custom pacer for potentially more efficient pacing // This is a simplified example; a truly custom pacer might involve more complex logic pacer := vegeta.Pacer(func(rate vegeta.Rate) time.Duration { return time.Second / time.Duration(rate.Freq) }) rate := vegeta.Rate{Freq: 500, Sample: 1 * time.Minute} // 500 requests per minute duration := 30 * time.Second err := attacker.Attack(vegeta.NewTarget(target), rate, duration, pacer, "efficient pacing tuning") if err != nil { log.Fatalf("Error during efficient pacing attack: %v", err) } fmt.Println("Efficient pacing tuning attack completed.") } ``` -------------------------------- ### LinearPacer Structure and Usage Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/05-pacers.md Defines the LinearPacer struct, its fields, and provides examples of its usage in setting up load tests with a ramp-up or ramp-down rate. ```APIDOC ## LinearPacer Increases request rate linearly over time using the equation: ``` R(t) = StartAt + Slope × t ``` ### Fields | Field | Type | Description | |-------|------|-------------| | StartAt | `Rate` | Initial request rate | | Slope | `float64` | Rate increase per second | ### Methods - `Pace(elapsed time.Duration, hits uint64) (time.Duration, bool)` - Determines wait time - `Rate(elapsed time.Duration) float64` - Returns current rate in req/s ### Examples ```go // Ramp from 10 req/s to 1000 req/s over 100 seconds // Slope = (1000-10)/100 = 9.9 req/s per second pacer := vegeta.LinearPacer{ StartAt: vegeta.Rate{Freq: 10, Per: time.Second}, Slope: 9.9, } // Slow ramp up: 100 to 200 req/s over 10 minutes pacer := vegeta.LinearPacer{ StartAt: vegeta.Rate{Freq: 100, Per: time.Second}, Slope: 0.0167, // 100 req/s additional per 10 minutes } // Ramp down (negative slope) pacer := vegeta.LinearPacer{ StartAt: vegeta.Rate{Freq: 500, Per: time.Second}, Slope: -5, // Decrease by 5 req/s per second } ``` ### Usage Example ```go attacker := vegeta.NewAttacker() targeter := vegeta.NewStaticTargeter(vegeta.Target{ Method: "GET", URL: "http://example.com", }) pacer := vegeta.LinearPacer{ StartAt: vegeta.Rate{Freq: 100, Per: time.Second}, Slope: 10, // Increase by 10 req/s per second } results := attacker.Attack(targeter, pacer, 120*time.Second, "ramp-up") var metrics vegeta.Metrics for res := range results { metrics.Add(res) } metrics.Close() fmt.Printf("Min rate: %.2f, Max rate: %.2f\n", metrics.Rate*0.1, metrics.Rate*10) ``` ``` -------------------------------- ### Configure TLS with Client Certificates Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/09-quick-start.md Load and use client certificates for mutual TLS authentication during load tests. Ensure the certificate and key files are correctly specified. ```go import "crypto/tls" cert, _ := tls.LoadX509KeyPair("client.crt", "client.key") tlsConfig := &tls.Config{ Certificates: []tls.Certificate{cert}, } attacker := vegeta.NewAttacker( vegeta.TLSConfig(tlsConfig), ) ``` -------------------------------- ### Process Vegeta Results Incrementally Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/09-quick-start.md Starts a Vegeta attack and processes results as they arrive. This is useful for real-time monitoring and immediate feedback during a test. ```go results := attacker.Attack(targeter, pacer, duration, "test") successCount := 0 errorCount := 0 for res := range results { if res.Code >= 200 && res.Code < 400 { successCount++ } else if res.Error != "" { errorCount++ fmt.Printf("Error: %v\n", res.Error) } metrics.Add(res) } metrics.Close() ``` -------------------------------- ### Get Pixel Ratio Source: https://github.com/tsenart/vegeta/blob/master/lib/plot/testdata/TestPlot.golden.html Retrieves the device's pixel ratio, which is important for rendering graphics at the correct resolution across different screens. ```javascript en.pxRatio = y ``` -------------------------------- ### HTTP File Targets Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/MANIFEST.md Load targets from an HTTP file. Each line in the file should be a URL to be attacked. ```go package main import ( "fmt" "log" vegeta "github.com/tsenart/vegeta/lib" ) func main() { targets, err := vegeta.NewTargetsFromFile("targets.txt") if err != nil { log.Fatalf("Error loading targets: %v", err) } attacker := vegeta.NewAttacker() err = attacker.Attack(targets, vegeta.DefaultPacer, vegeta.DefaultDuration, "http file targets attack") if err != nil { log.Fatalf("Error during attack: %v", err) } fmt.Println("HTTP file targets attack completed.") } ``` -------------------------------- ### Configure Custom Rate Pacer with Jitter Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/09-quick-start.md Use PacerFunc to implement a custom pacing strategy. This example targets a specific rate with random jitter. ```go // Custom pacer with jitter import "math/rand" pacer := vegeta.PacerFunc(func(elapsed time.Duration, hits uint64) (time.Duration, bool) { // Target 100 req/s with random jitter targetInterval := time.Second / 100 jitter := time.Duration(rand.Intn(20)-10) * time.Millisecond if hits == 0 { return 0, false } expectedHits := float64(elapsed) / float64(targetInterval) if float64(hits) >= expectedHits { return targetInterval + jitter, false } return 0, false }) ``` -------------------------------- ### Configure Redirects Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/01-attacker.md Sets the maximum number of redirects to follow. Use -1 to not follow redirects but mark as success. Defaults to 10. ```go func Redirects(n int) func(*Attacker) ``` -------------------------------- ### Configure Linear Ramping Rate Pacer Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/09-quick-start.md Use LinearPacer to gradually increase the request rate over time. Define the starting rate and the slope of increase. ```go // Start at 100, increase by 5 req/s per second // After 100 seconds: 100 + 5*100 = 600 req/s pacer := vegeta.LinearPacer{ StartAt: vegeta.Rate{Freq: 100, Per: time.Second}, Slope: 5, } ``` -------------------------------- ### TLS/HTTPS - Basic HTTPS Attack Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/MANIFEST.md Shows a basic Vegeta attack targeting an HTTPS endpoint. Ensure the target URL starts with 'https://'. ```go package main import ( "fmt" "log" vegeta "github.com/tsenart/vegeta/lib" ) func main() { target := "https://localhost:8443/" attacker := vegeta.NewAttacker() err := attacker.Attack(vegeta.NewTarget(target), vegeta.DefaultPacer, vegeta.DefaultDuration, "basic https attack") if err != nil { log.Fatalf("Error during HTTPS attack: %v", err) } fmt.Println("Basic HTTPS attack completed.") } ``` -------------------------------- ### Basic Vegeta Attack Source: https://github.com/tsenart/vegeta/blob/master/_autodocs/09-quick-start.md Demonstrates the minimal pattern for running a Vegeta load test. It includes creating an attacker, defining targets, setting a request rate, running the attack, collecting metrics, and reporting the results. ```go package main import ( "fmt" "time" vegeta "github.com/tsenart/vegeta/v12/lib" ) func main() { // Create attacker attacker := vegeta.NewAttacker() // Provide targets targeter := vegeta.NewStaticTargeter( vegeta.Target{ Method: "GET", URL: "http://localhost:8080/api", }, ) // Set rate: 100 requests per second pacer := vegeta.ConstantPacer{Freq: 100, Per: time.Second} // Run attack for 10 seconds results := attacker.Attack(targeter, pacer, 10*time.Second, "test") // Collect results var metrics vegeta.Metrics for res := range results { metrics.Add(res) } metrics.Close() // Print report vegeta.NewTextReporter(&metrics).Report(os.Stdout) } ```