英文:
Parsing GET parameters from a file to a NewRequest call in Go
问题
我目前正在尝试将GET参数从文件传递给httptest.NewRequest()函数调用。文件的内容如下:
varOne=x&varTwo=y
代码如下:
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")
}
}
然而,它似乎无法正确解析参数。当在浏览器中输入标准URL时(例如http://localhost:8000/check?varOne=x&varTwo=y),返回的是正确的值,但在上述测试中却不是。我在文件中格式化有误吗?
英文:
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?
答案1
得分: 2
请注意,NewRequest 中的第三个参数是请求体,而不是查询参数。正如 Volker 已经指出的那样,你可能想要使用表单字段发送所有内容 或者 使用以下方式使用查询参数:
req := httptest.NewRequest(http.MethodGet, "/check?"+string(b), nil)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论