2

So I've seen several posts saying you're supposed to put the targets in a temp file and the body in a .json file, but I need to send lots of random data to my site, and ideally I don't want to be constantly writing new random data to these files --so I'd like to do it all in one file. If this is just impossible and I have to use multiple files, please let me know.

All I'm trying to do right now is send a POST request to a webpage that is simply a form with 4 inputs: title, number, volume, and year. I have the following code, but right now it's not sending values. It's sending a payload, but one that has no values. Meaning that a key [] and value "" keep getting stored in my map on the backend. Can anyone see the reason it's sending blanks? Could anyone tell me how I should go about fixing it?

package main

import (
    "encoding/json"
    "fmt"
    "time"

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

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

        tgt.Method = "POST"

        tgt.URL = "http://localhost:8080/create.html"

        payload := map[string]string{
            "title":  "junk",
            "number": "junk2",
            "volume": "junk3",
            "year":   "junk4",
        }
        body, _ := json.Marshal(payload)
        tgt.Body = []byte(body)
        return nil
    }
}

func main() {
    rate := vegeta.Rate{Freq: 100, Per: 2 * time.Second}
    duration := 10 * time.Second
    targeter := NewCustomTargeter()
    attacker := vegeta.NewAttacker()
    var metrics vegeta.Metrics
    for res := range attacker.Attack(targeter, rate, duration, "Load Test") {
        metrics.Add(res)
    }
    metrics.Close()
    fmt.Printf("%+v  \n", metrics)

}
r.rodriguez
  • 35
  • 1
  • 5

1 Answers1

0

You need to do few stuff to make attacker able to send data in FormData format.

First, set the Content-type header value to application/x-www-form-urlencoded. You might need to import net/http package.

header := http.Header{}
header.Set("Content-type", "application/x-www-form-urlencoded")
tgt.Header = header

Then, set put the data into url.Values format. Pass the encoded value of it into tgt.Body. You also need to import net/url package.

form := url.Values{}
form.Set("title", "junk")
form.Set("number", "junk2")
form.Set("volume", "junk3")
form.Set("year", "junk4")

tgt.Body = []byte(form.Encode())

Additional notes

On the data preparation, we can also use map literal style.
But since url.Values is an alias of map[string][]string (not map[string]string),
might need some adjustment.

form := url.Values{
    "title":  []string{"junk"},
    "number": []string{"junk2"},
    "volume": []string{"junk3"},
    "year":   []string{"junk4"},
}
novalagung
  • 10,905
  • 4
  • 58
  • 82