GoWeb开发:003.Gin接收数据

126 阅读1分钟

接收Url参数

r.GET("/hello", func(c *gin.Context) {
  //参数未传递,默认为101
  userId := c.DefaultQuery("id", "101")
  userName := c.Query("username")

  result := fmt.Sprintf("用户Id: %s,用户名:%s", userId, userName)
  c.String(200, result)
})

示例:

$ curl http://localhost:8081/hello
用户Id: 101,用户名:

$ curl 'http://localhost:8081/hello?id=110&username=jim'
用户Id: 110,用户名:jim

接收路由参数

r.GET("/user/:id", func(c *gin.Context) {
  userId := c.Param("id")
  c.String(200, userId)
})

示例:

$ curl http://localhost:8081/user/112
112

$ curl http://localhost:8081/user
404 page not found

$ curl http://localhost:8081/user/hello
hello

接收Post参数

r.POST("/user/add", func(c *gin.Context) {
  userId := c.PostForm("id")
  userName := c.PostForm("username")
  result := fmt.Sprintf("用户Id: %s,用户名:%s", userId, userName)
  c.String(200, result)
})

示例:

$ curl -X POST -d 'id=110&username=jie' http://localhost:8081/user/add
用户Id: 110,用户名:jie

$ curl -X POST -d 'id=110' http://localhost:8081/user/add
用户Id: 110,用户名:

$ curl -X POST -d 'username=jie' http://localhost:8081/user/add
用户Id: ,用户名:jie

接受JSON数据

type User struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

r.POST("/user/login", func(c *gin.Context) {
  json := make(map[string]interface{})
  c.BindJSON(&json)
  c.JSON(200, gin.H{
    "username": json["username"],
    "password": json["password"],
  })
})

r.POST("/user/register", func(c *gin.Context) {
  user := User{}
  c.BindJSON(&user)
  c.JSON(200, gin.H{
    "username": user.Username,
    "password": user.Password,
  })
})

示例:

$ curl -H "Content-Type: application/json" -X POST -d '{"username":"jie","password":"123456"}' http://localhost:8081/user/login
{"password":"123456","username":"jie"}

$ curl -H "Content-Type: application/json" -X POST -d '{"username":"jie","password":"123456"}' http://localhost:8081/user/register
{"password":"123456","username":"jie"}