go : gin 绑定uri 用户信息

背景:
本文介绍如何使用gin框架 绑定uri信息
代码:

package main

import "github.com/gin-gonic/gin"

type Person struct {
	ID   string `uri:"id" binding:"required,uuid"`
	Name string `uri:"name" binding:"required"`
}

func main() {
	route := gin.Default()
	route.GET("/:name/:id", func(c *gin.Context) {
		var person Person
		if err := c.ShouldBindUri(&person); err != nil {
			c.JSON(400, gin.H{"msg": err})
			return
		}
		c.JSON(200, gin.H{"name": person.Name, "uuid": person.ID})
	})
	route.Run(":8088")
}

测试
1.使用定义格式/name/id

curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8088 (#0)
> GET /thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3 HTTP/1.1
> Host: localhost:8088
> User-Agent: curl/7.54.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=utf-8
< Date: Thu, 05 Dec 2019 10:25:55 GMT
< Content-Length: 67
< 
{"name":"thinkerou","uuid":"987fbc97-4bed-5078-9f07-9141ba07c9f3"}

2.不绑定uuid 仅/name测试

->curl -v localhost:8088/thinkerou/not-uuid
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8088 (#0)
> GET /thinkerou/not-uuid HTTP/1.1
> Host: localhost:8088
> User-Agent: curl/7.54.0
> Accept: */*
> 
< HTTP/1.1 400 Bad Request
< Content-Type: application/json; charset=utf-8
< Date: Thu, 05 Dec 2019 10:26:36 GMT
< Content-Length: 13
< 
{"msg":[{}]}
* Connection #0 to host localhost left intact

服务端日志

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值