« Back to Index

Go: Custom Vegeta Attack

View original Gist on GitHub

Tags: #go #performance

Custom Golang Vegeta Attack.go

package main

import (
	"fmt"
	"math/rand"
	"time"

	vegeta "github.com/tsenart/vegeta/lib"
)

// randNDigits produces a random number N digits long.
//
// e.g. the args (0000, 9999) produces a random number inbetween that range and
// would also be four digits in length.
//
func randNDigits(low, hi int) int {
	return low + rand.Intn(hi-low)
}

func NewCustomTargeter() vegeta.Targeter {
	return func(tgt *vegeta.Target) error {
		if tgt == nil {
			return vegeta.ErrNilTarget
		}

		payload := fmt.Sprintf(`{"id": %d}`, randNDigits(0000, 9999))

		tgt.Method = "POST"
		tgt.URL = "https://httpbin.org/post"
		tgt.Body = []byte(payload)

		return nil
	}
}

func main() {
	/*
		targeter := vegeta.NewStaticTargeter(vegeta.Target{
			Method: "GET",
			URL:    "http://localhost:9100/",
		})
	*/

	targeter := NewCustomTargeter()
	attacker := vegeta.NewAttacker()

	rate := vegeta.Rate{Freq: 100, Per: time.Second}
	duration := 4 * time.Second

	var metrics vegeta.Metrics
	for res := range attacker.Attack(targeter, rate, duration, "Load Test") {
		metrics.Add(res)
	}
	metrics.Close()

	fmt.Printf("%+v\n", metrics)

	/*
		{
		  Latencies:{
		    Total:43.957975822s
		    Mean:109.894939ms
		    P50:84.906555ms
		    P95:290.766111ms
		    P99:343.919767ms
		    Max:373.975574ms
		    estimator:0xc000384058
		  }
		  Histogram:<nil>
		  BytesIn:{
		    Total:158322
		    Mean:395.805
		  }
		  BytesOut:{
		    Total:4761
		    Mean:11.9025
		  }
		  Earliest:2020-09-03 17:02:46.839298954 +0100 BST m=+0.011156791
		  Latest:2020-09-03 17:02:50.829355988 +0100 BST m=+4.001213825
		  End:2020-09-03 17:02:51.012499584 +0100 BST m=+4.184357421
		  Duration:3.990057034s
		  Wait:183.143596ms
		  Requests:400
		  Rate:100.24919358082539
		  Throughput:95.84969318860665
		  Success:1
		  StatusCodes:map[200:400]
		  Errors:[]
		  errors:map[]
		  success:400
		}
	*/
}

go.mod

module test_vegeta

go 1.14

require (
	github.com/influxdata/tdigest v0.0.1 // indirect
	github.com/mailru/easyjson v0.7.6 // indirect
	github.com/tsenart/vegeta v12.7.0+incompatible
	golang.org/x/net v0.0.0-20200822124328-c89045814202 // indirect
)