V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
kanhongj
V2EX  ›  问与答

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

  •  
  •   kanhongj · 2021-08-30 23:23:12 +08:00 · 1348 次点击
    这是一个创建于 940 天前的主题,其中的信息可能已经有所发展或是发生改变。

    就是最近想学 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:

    8 条回复    2021-08-31 11:41:22 +08:00
    Jwyt
        1
    Jwyt  
       2021-08-30 23:31:08 +08:00
    TestJson 的 id 和 page 首字母大写
    Dreax
        2
    Dreax  
       2021-08-30 23:32:30 +08:00
    把 struct 里的 fields 首字母大写
    kanhongj
        3
    kanhongj  
    OP
       2021-08-30 23:54:31 +08:00 via iPhone
    @Jwyt 哦哦好的👌我试试
    kanhongj
        4
    kanhongj  
    OP
       2021-08-30 23:54:41 +08:00 via iPhone
    @Dreax 谢谢谢谢
    kanhongj
        5
    kanhongj  
    OP
       2021-08-30 23:54:53 +08:00 via iPhone
    @Jwyt 谢谢
    hq136234303
        6
    hq136234303  
       2021-08-31 09:43:56 +08:00
    go 首字母大写 指代访问范围的。小写是私有变量。
    anyxchachapoly
        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 那样的规范,那当我没说
    vZexc0m
        8
    vZexc0m  
       2021-08-31 11:41:22 +08:00
    from 可还行
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5014 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 09:46 · PVG 17:46 · LAX 02:46 · JFK 05:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.