
就是最近想学 GIN, 然后网上找了资料,说用 ShouldBindJSON() 去解析 JSON, 自己敲了运行了,但是没得想要的结果啊。查的类似教程也是这套代码。
go version go1.17 linux/amd64
import ( "github.com/gin-gonic/gin" "fmt" "net/http" ) type TestJson struct{ id string `from:"id" json:"id" binding:"required"` page string `from:"page" json:"page" binding:"required"` } func handle_post(c *gin.Context){ // json := make(map[string]interface{}) var test_json TestJson // c.BindJSON(&json) // c.ShouldBindJSON(&test_json) if err := c.ShouldBindJSON(&test_json); err !=nil { c.AbortWithStatusJSON( http.StatusInternalServerError, gin.H{"error": err.Error()}) return } fmt.Printf("%v\n", test_json) fmt.Printf("id:%s; page:%s\n", test_json.id, test_json.page) c.JSON( http.StatusOK, gin.H{"msg" : "OK"}) return } func main() { router := gin.Default() router.POST("/from_post", handle_post) router.Run(":8080") } [GIN-debug] Listening and serving HTTP on :8080 { } id:; page: [GIN] 2021/08/30 - 23:11:03 | 200 | 157.946s | 212.103.62.124 | POST "/from_post" 我发送 JSON 为 {"id":"123456", "page":"4"} 后台没得到数据啊~ 先谢谢各位了~ :blush:
1 Dockerfile 2021-08-30 23:31:08 +08:00 TestJson 的 id 和 page 首字母大写 |
2 Dreax 2021-08-30 23:32:30 +08:00 把 struct 里的 fields 首字母大写 |
6 hq136234303 2021-08-31 09:43:56 +08:00 go 首字母大写 指代访问范围的。小写是私有变量。 |
7 anyxchachapoly 2021-08-31 11:19:56 +08:00 btw 一般 var & method 走 camelcase (字首根据 visibility 决定),特殊 const (尤其 system api with public access ) all uppercase with snakecase,反之随意 算是很常见的 convention,如果有人想逼我拿出类似 psr 那样的规范,那当我没说 |
8 vZexc0m 2021-08-31 11:41:22 +08:00 from 可还行 |