将文件中的GET参数解析为Go中的NewRequest调用。

huangapple go评论193阅读模式
英文:

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

问题

我目前正在尝试将GET参数从文件传递给httptest.NewRequest()函数调用。文件的内容如下:

  1. varOne=x&varTwo=y

代码如下:

  1. func TestOne(t *testing.T) {
  2. te := &Template{
  3. templates: template.Must(template.ParseGlob("public/views/*.html")),
  4. }
  5. e := echo.New()
  6. e.Renderer = te
  7. file, err := os.Open("tests/params.txt")
  8. if err != nil {
  9. log.Fatal(err)
  10. }
  11. defer func() {
  12. if err = file.Close(); err != nil {
  13. log.Fatal(err)
  14. }
  15. }()
  16. b, err := ioutil.ReadAll(file)
  17. req := httptest.NewRequest(http.MethodGet, "/check", strings.NewReader(string(b)))
  18. rec := httptest.NewRecorder()
  19. c := e.NewContext(req, rec)
  20. fmt.Println(rec.Code)
  21. if assert.NoError(t, check(c)) {
  22. assert.Contains(t, rec.Body.String(), "Check")
  23. }
  24. }

然而,它似乎无法正确解析参数。当在浏览器中输入标准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:

  1. varOne=x&varTwo=y

The code looks like:

  1. func TestOne(t *testing.T) {
  2. te := &Template{
  3. templates: template.Must(template.ParseGlob("public/views/*.html")),
  4. }
  5. e := echo.New()
  6. e.Renderer = te
  7. file, err := os.Open("tests/params.txt")
  8. if err != nil {
  9. log.Fatal(err)
  10. }
  11. defer func() {
  12. if err = file.Close(); err != nil {
  13. log.Fatal(err)
  14. }
  15. }()
  16. b, err := ioutil.ReadAll(file)
  17. req := httptest.NewRequest(http.MethodGet, "/check", strings.NewReader(string(b)))
  18. rec := httptest.NewRecorder()
  19. c := e.NewContext(req, rec)
  20. fmt.Println(rec.Code)
  21. if assert.NoError(t, check(c)) {
  22. assert.Contains(t, rec.Body.String(), "Check")
  23. }
  24. }

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 已经指出的那样,你可能想要使用表单字段发送所有内容 或者 使用以下方式使用查询参数:

  1. 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:

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

huangapple
  • 本文由 发表于 2021年5月31日 12:13:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/67767837.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定