有 go 比较熟悉的大佬吗?帮我瞧瞧怎么回事

2021-08-30 23:23:12 +08:00
 kanhongj

就是最近想学 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.946µs |  212.103.62.124 | POST     "/from_post"

我发送 JSON 为 {"id":"123456", "page":"4"} 后台没得到数据啊~ 先谢谢各位了~ :blush:

1384 次点击
所在节点    问与答
8 条回复
Jwyt
2021-08-30 23:31:08 +08:00
TestJson 的 id 和 page 首字母大写
Dreax
2021-08-30 23:32:30 +08:00
把 struct 里的 fields 首字母大写
kanhongj
2021-08-30 23:54:31 +08:00
@Jwyt 哦哦好的👌我试试
kanhongj
2021-08-30 23:54:41 +08:00
@Dreax 谢谢谢谢
kanhongj
2021-08-30 23:54:53 +08:00
@Jwyt 谢谢
hq136234303
2021-08-31 09:43:56 +08:00
go 首字母大写 指代访问范围的。小写是私有变量。
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 那样的规范,那当我没说
vZexc0m
2021-08-31 11:41:22 +08:00
from 可还行

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/798942

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX