Go gin框架:使用cURL测试查询和POST请求

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

Go gin-framework: Testing query and POST with cURL

问题

我正在尝试 gin 框架的 README 中的代码示例("Another example: query + post form"):

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

func main() {
	router := gin.Default()

	router.POST("/post", func(c *gin.Context) {
		id := c.Query("id")
		page := c.DefaultQuery("page", "0")
		name := c.PostForm("name")
		message := c.PostForm("message")

		fmt.Printf("id: %s; page: %s; name: %s; message: %s\n", id, page, name, message)
	})
	router.Run(":8080")
}

使用 cURL 测试代码:

curl -d "name=Maru&message=Nice" 0.0.0.0:8080/post?id=2&page=3

服务器返回:id: 2; page: 0; name: Maru; message: Nice

这个 curl 测试是正确的吗?为什么返回值中的 page 不等于 3?

英文:

I'm trying a code example in the README of gin framework ("Another example: query + post form"):

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

func main() {
	router := gin.Default()

	router.POST("/post", func(c *gin.Context) {
		id := c.Query("id")
		page := c.DefaultQuery("page", "0")
		name := c.PostForm("name")
		message := c.PostForm("message")

		fmt.Printf("id: %s; page: %s; name: %s; message: %s\n", id, page, name, message)
	})
	router.Run(":8080")
}

Testing the code with cURL:

curl -d "name=Maru&message=Nice" 0.0.0.0:8080/post?id=2&page=3

The server returns: id: 2; page: 0; name: Maru; message: Nice.

Is the curl testing correct? Why isn't page in the returned value equal to 3?

答案1

得分: 2

安培符号(&)是您的shell中的特殊字符。它会导致前一个命令在后台运行。您的shell将该命令解释为:

curl -d "name=Maru&message=Nice" 0.0.0.0:8080/post?id=2 & # 在后台运行curl
page=3 # 设置page=3

转义该字符将给您预期的结果:

curl -d "name=Maru&message=Nice" "0.0.0.0:8080/post?id=2&page=3"

<!-- -->

curl -d "name=Maru&amp;message=Nice" 0.0.0.0:8080/post?id=2\&amp;page=3
英文:

The ampersand (&amp;) is a special character in your shell. It causes the previous command to run in the background. Your shell was interpreting the command as:

curl -d &quot;name=Maru&amp;message=Nice&quot; 0.0.0.0:8080/post?id=2 &amp; # run curl in the background
page=3 # set page=3

Escaping the character will give you the expected result:

curl -d &quot;name=Maru&amp;message=Nice&quot; &quot;0.0.0.0:8080/post?id=2&amp;page=3&quot;

<!-- -->

curl -d &quot;name=Maru&amp;message=Nice&quot; 0.0.0.0:8080/post?id=2\&amp;page=3

huangapple
  • 本文由 发表于 2016年4月24日 00:21:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/36813307.html
匿名

发表评论

匿名网友

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

确定