前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >go : gin 绑定uri 用户信息

go : gin 绑定uri 用户信息

原创
作者头像
IT工作者
发布2022-07-26 11:00:45
2530
发布2022-07-26 11:00:45
举报
文章被收录于专栏:程序技术知识

本文介绍如何使用gin框架 绑定uri信息

代码:

代码语言:javascript
复制
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

代码语言:javascript
复制
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 July 2022 10:25:55 GMT
< Content-Length: 67
< 
{"name":"thinkerou","uuid":"987fbc97-4bed-5078-9f07-9141ba07c9f3"}

2.不绑定uuid 仅/name测试

代码语言:javascript
复制
->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 July 2022 10:26:36 GMT
< Content-Length: 13
< 
{"msg":[{}]}
* Connection #0 to host localhost left intact

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档