本文是gin介绍和使用的第一篇文章。
一、简要介绍
Gin的官方说明如下:
Gin is a web framework written in Go (Golang). It features a martini-like API with much better
performance, up to 40 times faster thanks to httprouter. If you need performance and good
productivity, you will love Gin.
简单来说,Gin是一个Go的微框架,基于 httprouter,提供了类似martini(也是一个go web框架)但更好性能的API服务。
Gin具有运行速度快、良好的分组路由、合理的异常捕获和错误处理、优良的中间件支持和 json处理支持等优点,是一款非常值得推荐的web框架。
借助框架开发,我们不仅可以省去很多常用的封装带来的时间,也有助于良好的团队编码风格的和编码规范的养成。
二、使用详解
1.安装
要安装Gin包,首先需要安装Go((Go版本1.10+)并设置Go工作区
下载并安装:
go get -u github.com/gin-gonic/gin
在代码中导入它
import "github.com/gin-gonic/gin"
2. 简单示例:
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() // listen and serve on 0.0.0.0:8080
}
简单几行代码,就实现了一个web服务。
首先,使用gin的Default方法创建一个路由handle;
然后,通过HTTP方法绑定路由规则和路由函数;
最后,启动路由的Run方法监听端口。
不同于net/http库的路由函数,gin进行了封装,把request和response都封装到gin.Context的上下文环境。
3. 常用请求方法
除了GET方法,gin也支持POST,PUT,DELETE,OPTION等常用的restful方法:
func main() {
// Creates a gin router with default middleware:
// logger and recovery (crash-free) middleware
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)
// By default it serves on :8080 unless a
// PORT environment variable was defined.
router.Run()
// router.Run(":3000") for a hard coded port
}
4. 获取路径中的参数
gin的路由来自httprouter库。因此httprouter具有的功能,gin也具有,不过gin不支持路由正则表达式:
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
// This handler will match /user/john but will not match /user/ or /user
router.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
// Howerer, this one will match /user/john/ and also /user/john/send
// if no other routers match /user/john, it will redirect to /user/john/
router.GET("/user/:name/*action", func(c *gin.Cont
最后
以上就是健忘钢笔最近收集整理的关于gin c.html(),go web框架gin介绍和使用(一)的全部内容,更多相关gin内容请搜索靠谱客的其他文章。
发表评论 取消回复