壹影博客.
我在下午4点钟开始想你
GolangWeb框架Gin快速入门
  • 2024-8-5日
  • 1评论
  • 542围观

GolangWeb框架Gin快速入门

Gin是一个轻量级的Go语言Web框架,它具有高性能和简洁的设计。由于其快速的路由匹配和处理性能,Gin成为Go语言中最受欢迎的Web框架之一。

 特点:

快速和轻量:Gin框架的设计注重性能和效率,采用了一些优化措施,使其成为一个快速而轻量级的框架。
路由和中间件:Gin提供了强大的路由功能,支持参数传递,路由分组等特性。同时,它支持中间件的使用,可以方便的在请求处理过程中执行一系列的操作,比如身份验证,日志记录等。
json解析:Gin内置了对json的解析和序列化支持,使得处理json数据变得简单而高效。
支持插件:Gin允许开发者通过插件来扩展框架的功能,这样可以根据项目的需求进行灵活定

Github地址:https://github.com/gin-gonic/gin
中文文档:https://gin-gonic.com/zh-cn/docs/

 一、安装

命令安装

go get github.com/gin-gonic/gin@latest

导入包到项目

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

二、快速使用

简单启动配置

package main

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

func main() {
    ginService := gin.Default() //默认获取
    ginService.GET("/hello", func(context *gin.Context) {
        context.JSON(200, gin.H{"msg": "hello,world"})
    })
    //启动服务
    ginService.Run(":1001") //启动端口
}

三、路由配置

 如下代码案例 配置路由直接访问
http://localhost:8848/link

ginService := gin.Default()
ginService.GET("/link", func(context *gin.Context) {
    context.Redirect(http.StatusMovedPermanently, "https://bk.yyge.net")
})
//启动服务
ginService.Run(":8848")

//http://localhost:8848/link

四、Get请求 - 带参数 

一般两种方式

//第一种
// http://localhost:8848/user/info?userId=121212&userName=nihaohi
ginService := gin.Default()
ginService.GET("/user/info", func(context *gin.Context) {
    userId := context.Query("userId")
    userName := context.Query("userName")
    context.JSON(http.StatusOK, gin.H{
        "userId":   userName,
        "userName": userId,
    })
})
//启动服务
ginService.Run(":8848")
//第二种
//http://localhost:8848/user/info/121212/nihao55hi
ginService := gin.Default()
ginService.GET("/user/info/:userId/:userName", func(context *gin.Context) {
    userId := context.Param("userId")
    userName := context.Param("userName")
    context.JSON(http.StatusOK, gin.H{
        "userId":   userName,
        "userName": userId,
    })
})
//启动服务
ginService.Run(":8848")

五、Post请求 - 带参数

Post Json传输

ginService := gin.Default()
ginService.POST("/json", func(context *gin.Context) {
    b, _ := context.GetRawData()
    var m map[string]interface{}
    _ = json.Unmarshal(b, &m)
    context.JSON(http.StatusOK,m)
})
//启动服务
ginService.Run(":8848")

POST请求 表单

//表单传输 前端通过表单
ginService := gin.Default()
ginService.POST("/user/info", func(context *gin.Context) {
    userId := context.PostForm("userId")
    userName := context.PostForm("userName")
    context.JSON(http.StatusOK, gin.H{
        "userId":   userId,
        "userName": userName,
    })
})
//启动服务
ginService.Run(":8848")

六、404处理

ginService := gin.Default()
//加载静态页面
ginService.LoadHTMLGlob("templates/*")
ginService.NoRoute(func(context *gin.Context) {
    context.HTML(http.StatusNotFound, "404.html", nil)
})
//启动服务
ginService.Run(":8848")

//注意:要在根目录下有templates/404.html 文件

7.路由组定义

 见如下图片示例

八、拦截器配置

package main

import (
    "github.com/gin-gonic/gin"
    "log"
    "net/http"
)

// 自定义拦截器
func interseptor() gin.HandlerFunc {
    return func(context *gin.Context) {
        context.Set("usersesion", "userId-1")
        if xxx {
            context.Next() //放行
        }
        context.Abort() //阻止
    }
}

func main() {
    ginService := gin.Default()
    //加载静态页面
    ginService.LoadHTMLGlob("templates/*")
    ginService.GET("/user/info", interseptor(), func(context *gin.Context) {
        //取出中间件中的值
        usersesion := context.MustGet("usersesion").(string)
        log.Println(usersesion)

        context.JSON(http.StatusOK, gin.H{
            "usersesion": usersesion,
        })
    })
    //启动服务
    ginService.Run(":8848")
}

end ~~
by 壹影

发表评论

RobertJax

Lv.1 @回复 沙发

Unleash your inner CEO

现在在游戏中获得新的代币仓鼠快打
每日分发到你的钱包里
加入我们的项目notreward.pro 并接收转基因食品

[url=https://notreward.pro]Hamster Airdrop[/url]

渝ICP备19011465号 | 渝ICP备19011465号-1