flowermia
flowermia

Reputation: 409

Parsing GET parameters from a file to a NewRequest call in Go

I'm currently trying to pass GET parameters from a file to a httptest.NewRequest() call. The content of the file looks like:

varOne=x&varTwo=y

The code looks like:

func TestOne(t *testing.T) {
    te := &Template{
        templates: template.Must(template.ParseGlob("public/views/*.html")),
    }
    e := echo.New()
    e.Renderer = te

    file, err := os.Open("tests/params.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = file.Close(); err != nil {
            log.Fatal(err)
        }
    }()

    b, err := ioutil.ReadAll(file)

    req := httptest.NewRequest(http.MethodGet, "/check", strings.NewReader(string(b)))
    rec := httptest.NewRecorder()
    c := e.NewContext(req, rec)
    fmt.Println(rec.Code)
    if assert.NoError(t, check(c)) {
        assert.Contains(t, rec.Body.String(), "Check")
    }
}

However, it doesn't seem to be parsing the parameters correctly. The standard URL returns the correct values when entered in a browser (e.g. http://localhost:8000/check?varOne=x&varTwo=y) but not when being tested like above. Have I formatted them wrong in the file?

Upvotes: 0

Views: 1298

Answers (1)

Gregor Zurowski
Gregor Zurowski

Reputation: 2346

Please note that the third argument in NewRequest is a request body, not query parameters. As Volker already pointed out, you probably want to either send everything using form fields or use query parameters as follows:

req := httptest.NewRequest(http.MethodGet, "/check?" + string(b), nil)

Upvotes: 2

Related Questions