Golang学习笔记之WEB框架(gin)基本使用

栏目: Go · 发布时间: 6年前

内容简介:gin是Go语言写的一个web框架,API性能超强,运行速度号称较httprouter要快40倍。封装比较优雅,API友好,源码注释比较明确,具有快速灵活,容错方便等特点。官方给的一个示例程序

gin是 Go 语言写的一个web框架,API性能超强,运行速度号称较httprouter要快40倍。封装比较优雅,API友好,源码注释比较明确,具有快速灵活,容错方便等特点。

Github地址: https://github.com/gin-gonic/gin

gin的安装: go get github.com/gin-gonic/gin

API

gin.Default()

创建路由

gin.DisableConsoleColor()

禁用控制台颜色

gin.SetMode()

设置gin模式。参数可以传递:gin.DebugMode、gin.ReleaseMode、gin.TestMode。

路由的方法为:假定我们先创建一个路由

router := gin.Default()

获取的方式可以为

router.GET("/someGet", getting)
    router.POST("/somePost", posting)
    router.PUT("/somePut", putting)
    router.DELETE("/someDelete", deleting)
    router.PATCH("/somePatch", patching)
    router.HEAD("/someHead", head)
    router.OPTIONS("/someOptions", options)

router.Group(s string)
分组,s为组名

一、第一个gin程序

官方给的一个示例程序

package main
import "github.com/gin-gonic/gin"
func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run(":8080") // listen and serve on 0.0.0.0:8080
}

运行程序,在浏览器上访问: http://127.0.0.1:8080/ping

Golang学习笔记之WEB框架(gin)基本使用

c.String用来返回字符串。

c.JSON用来返回Json。

gin的功能不只是简单输出Json数据。它是一个轻量级的WEB框架,支持RestFull风格API,支持GET,POST,PUT,PATCH,DELETE,OPTIONS 等http方法,支持文件上传,分组路由,Multipart/Urlencoded FORM,以及支持JsonP,参数处理等等功能,这些都和WEB紧密相关,通过提供这些功能,使开发人员更方便地处理WEB业务。不同于 net/http库的路由函数,gin进行了封装,把request和response都封装到 gin.Context的上下文环境。

二、快速匹配参数

Gin框架可以快速的匹配参数

func main() {
    router := gin.Default()
    router.GET("/user/:name/:password", HinHandler)
    router.Run(":8081")
}
//HinHandler 解构传过来的name和password
func HinHandler(c *gin.Context) {
    name := c.Param("name")
    pwd := c.Param("password")
    //内部提供方法用来返回字符串
    c.String(http.StatusOK, "你好 %s,你的密码为%s", name, pwd)
}

运行程序在浏览器上访问: http://127.0.0.1:8081/user/huangzhe/123

Golang学习笔记之WEB框架(gin)基本使用

三、Gin获取普通get参数

func main() {
    //修改模式
    gin.SetMode(gin.ReleaseMode)
    //Default方法创建一个路由handler。
    router := gin.Default()
    router.GET("/user", GetHandler)
    router.Run(":8081")
}
//GetHandler 使用get方式获取对应键的值
func GetHandler(c *gin.Context) {
    name := c.DefaultQuery("name", "Guest") //找不到name给它一个默认值Guest
    password := c.Query("password")         //找不到直接赋空
    //GetQuery返回两个参数,第一个是找到的对应键的值,第二个是是否找到error类型
    id, exist := c.GetQuery("id")
    if !exist {
        name = "the key is not exist"
    }
    c.Data(http.StatusOK, "text/plain",
        []byte(fmt.Sprintf("get success! %s %s %s", name, password, id)))
}
Golang学习笔记之WEB框架(gin)基本使用

四、分组

//分组
    //组内成员访问为http://127.0.0.1:8080/admin/...
    v1 := router.Group("admin")
    
    {
        //访问为http://127.0.0.1:8080/admin/ping
        v1.GET("/ping", api.HelloPage)
        v1.GET("/welcome", api.LoginHandler)
        v1.GET("/getquery",api.GetHandler)
    }

五、Gin默认路由

我们可以自定义404错误

func main() {
    //修改模式
    gin.SetMode(gin.ReleaseMode)

    //Default方法创建一个路由handler。
    router := gin.Default()

    //设定请求url不存在的返回值
    router.NoRoute(NoResponse)

    router.GET("/user", GetHandler)
    router.Run(":8081")
}
//NoResponse 请求的url不存在,返回404
func NoResponse(c *gin.Context) {
    //返回404状态码
    c.JSON(http.StatusNotFound, gin.H{
        "status": 404,
        "error":  "404, page not exists!",
    })
}
//GetHandler 使用get方式获取对应键的值
func GetHandler(c *gin.Context) {
    name := c.DefaultQuery("name", "Guest") //找不到name给它一个默认值Guest
    password := c.Query("password")         //找不到直接赋空
    //GetQuery返回两个参数,第一个是找到的对应键的值,第二个是是否找到error类型
    id, exist := c.GetQuery("id")
    if !exist {
        name = "the key is not exist"
    }
    c.Data(http.StatusOK, "text/plain",
        []byte(fmt.Sprintf("get success! %s %s %s", name, password, id)))
}

我们去请求一个并不存在的url: http://127.0.0.1:8081/us

Golang学习笔记之WEB框架(gin)基本使用

六、Gin获取普通post参数

我这里是使用RESTClient来模拟的,在Firefox上附加组件

Golang学习笔记之WEB框架(gin)基本使用
func main() {
    //修改模式
    gin.SetMode(gin.ReleaseMode)

    //Default方法创建一个路由handler。
    router := gin.Default()

    //设定请求url不存在的返回值
    router.NoRoute(NoResponse)

    router.POST("/user", PostLoginHandler)
    router.Run(":8081")
}

//NoResponse 请求的url不存在,返回404
func NoResponse(c *gin.Context) {
    //返回404状态码
    c.JSON(http.StatusNotFound, gin.H{
        "status": 404,
        "error":  "404, page not exists!",
    })
}

//PostLoginHandler 获取参数
func PostLoginHandler(c *gin.Context) {
    name := c.PostForm("name")                       //找不到name直接返回0值
    password := c.DefaultPostForm("password", "888") //找不到password赋默认值
    sec, ok := c.GetPostForm("second")               //判断是否能找到,找不到返回false
    c.String(http.StatusOK, "hello %s %s %s", name, password, sec)
    log.Panicln(ok)
}

使用post需要添加头字段

Golang学习笔记之WEB框架(gin)基本使用

如下:

Golang学习笔记之WEB框架(gin)基本使用

七、中间件MiddleWare

注意,gin.Default() 默认是加载了一些框架内置的中间件的,而 gin.New() 则没有,根据需要自己手动加载中间件。

func MiddleWare(c *gin.Context) {
    fmt.Println("before request")
    c.Next()
}
func main() {
    //修改模式
    gin.SetMode(gin.ReleaseMode)

    //Default方法创建一个路由handler。
    router := gin.Default()

    //设定请求url不存在的返回值
    router.NoRoute(NoResponse)

    router.Use(MiddleWare)

    router.GET("/user", GetHandler)
    router.Run(":8081")
}

//NoResponse 请求的url不存在,返回404
func NoResponse(c *gin.Context) {
    //返回404状态码
    c.JSON(http.StatusNotFound, gin.H{
        "status": 404,
        "error":  "404, page not exists!",
    })
}

//GetHandler 使用get方式获取对应键的值
func GetHandler(c *gin.Context) {
    name := c.DefaultQuery("name", "Guest") //找不到name给它一个默认值Guest
    password := c.Query("password")         //找不到直接赋空
    //GetQuery返回两个参数,第一个是找到的对应键的值,第二个是是否找到error类型
    id, exist := c.GetQuery("id")
    if !exist {
        name = "the key is not exist"
    }
    c.Data(http.StatusOK, "text/plain",
        []byte(fmt.Sprintf("get success! %s %s %s", name, password, id)))
}

我们访问上面的url

Golang学习笔记之WEB框架(gin)基本使用

在终端上你会发现中间件已执行,我们可以在中间件里做验证或者⽇志记录

Golang学习笔记之WEB框架(gin)基本使用

c.Next()继续执行下面的函数

c.Abort()截断执行

八、文件服务

上传单个文件

func main() {
    router := gin.Default()
    // Set a lower memory limit for multipart forms (default is 32 MiB)
    // router.MaxMultipartMemory = 8 << 20  // 8 MiB
    router.POST("/upload", func(c *gin.Context) {
        // single file
        file, _ := c.FormFile("file")
        log.Println(file.Filename)

        // Upload the file to specific dst.
        // c.SaveUploadedFile(file, dst)

        c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
    })
    router.Run(":8080")
}

上传多个文件

func main() {
    router := gin.Default()
    // Set a lower memory limit for multipart forms (default is 32 MiB)
    // router.MaxMultipartMemory = 8 << 20  // 8 MiB
    router.POST("/upload", func(c *gin.Context) {
        // Multipart form
        form, _ := c.MultipartForm()
        files := form.File["upload[]"]
        for _, file := range files {
            log.Println(file.Filename)

            // Upload the file to specific dst.
            // c.SaveUploadedFile(file, dst)
        }
        c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
    })
    router.Run(":8080")
}

更多使用可以去Github去查: https://github.com/gin-gonic/gin


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms to Live By

Algorithms to Live By

Brian Christian、Tom Griffiths / Henry Holt and Co. / 2016-4-19 / USD 30.00

A fascinating exploration of how insights from computer algorithms can be applied to our everyday lives, helping to solve common decision-making problems and illuminate the workings of the human mind ......一起来看看 《Algorithms to Live By》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

SHA 加密
SHA 加密

SHA 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具