英文:
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&message=Nice" 0.0.0.0:8080/post?id=2\&page=3
英文:
The ampersand (&
) 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 "name=Maru&message=Nice" 0.0.0.0:8080/post?id=2 & # run curl in the background
page=3 # set page=3
Escaping the character will give you the expected result:
curl -d "name=Maru&message=Nice" "0.0.0.0:8080/post?id=2&page=3"
<!-- -->
curl -d "name=Maru&message=Nice" 0.0.0.0:8080/post?id=2\&page=3
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论