Gin框架初识

本文介绍Gin框架的安装与使用,包括GET与POST请求处理、参数获取与绑定等核心功能。通过实例演示如何搭建RESTful API。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于Gin的具体说明与源码:https://github.com/gin-gonic/gin

一.安装
命令行输入:go get github.com/gin-gonic/gin
安装位置:go的环境变量中配置的全局的lib目录

二:基本应用

1. GET
1)gin.Context中的Query方法:get的URL传参

func getQuery(context *gin.Context){

    userid := context.Query("userid")
    username := context.Query("username")

    context.String(http.StatusOK,userid+" "+username)
}
func main(){
    // 注册一个默认路由器
    router := gin.Default()

    //注册GET处理
    router.GET("/user", getQuery)

    //默认8080端口
    router.Run(":8088")
}

测试:URL:http://localhost:8088/user?userid=1&username=tyming
浏览器输出:1 tyming

2)gin.Context中的Param方法:RESRful风格URL传参

func getParam(context *gin.Context){

    userid := context.Param("userid")
    username := context.Param("username")

    context.String(http.StatusOK,userid+" "+username)
}
func main(){
    // 注册一个默认路由器
    router := gin.Default()

    //注册GET处理
    //router.GET("/user", getQuery)
    router.GET("/user/:userid/:username",getParam)
    //默认8080端口
    router.Run(":8088")
}

补充:/:varname必须匹配对应的,/*varname匹配后面的所有,同时不能用多个,否则编译报错
测试:URL:http://localhost:8088/user/1/tyming
页面输出:1 tyming

2. POST

*1)gin.Context中的PostForm方法:POST表单提交*
func post(context *gin.Context){

    username := context.PostForm("username")
    //设置默认值,没有值返回默认值
    password := context.DefaultPostForm("password","1234567890")

    context.JSON(200, gin.H{
        "status":  "posted",
        "username": username,
        "password": password,
    })
}
func main(){
    // 注册一个默认路由器
    router := gin.Default()

    //注册POST处理
    router.POST("/user",post)
    //默认8080端口
    router.Run(":8088")
}

测试:模拟post
这里写图片描述

2)参数绑定

type User struct {
    UserName string `form:"username"`
    PassWord string `form:"password"`
}
func bind(context *gin.Context){
    var user User

    if context.Bind(&user) == nil{

        context.JSON(http.StatusOK,gin.H{"username":user.UserName,"password":user.PassWord})
    }
}

func main(){
    // 注册一个默认路由器
    router := gin.Default()

    //注册POST处理器
    router.POST("/bind",bind)
    //默认8080端口
    router.Run(":8088")
}

测试:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值