Gin是一个golang的微框架,封装比较优雅,API友好,源码注释比较明确,具有快速灵活,容错方便等特点
对于golang而言,web框架的依赖要远比Python,Java之类的要小。自身的net/http足够简单,性能也非常不错
借助框架开发,不仅可以省去很多常用的封装带来的时间,也有助于团队的编码风格和形成规范
要安装Gin软件包,您需要安装Go并首先设置Go工作区。
1.首先需要安装Go(需要1.10+版本),然后可以使用下面的Go命令安装Gin。
go get -u github.com/gin-gonic/gin
- go get -u github.com/gin-gonic/gin
- go: go.mod file not found in current directory or any parent directory.
- 'go get' is no longer supported outside a module.
- To build and install a command, use 'go install' with a version,
- like 'go install example.com/cmd@latest'
- For more information, see https://golang.org/doc/go-get-install-deprecation
- or run 'go help get' or 'go help install'.
简单建立一个go.mod 文件,我这里是直接在hello目录下建立一个gindemo.go文件。进行包下载
- GOROOT=/usr/local/go #gosetup
- GOPATH=/Users/apple/go #gosetup
- /usr/local/go/bin/go mod tidy #gosetup
- go: finding module for package github.com/gin-gonic/gin
- go: found github.com/gin-gonic/gin in github.com/gin-gonic/gin v1.8.1
提示是已经下载最新的包是1.8.1版本的
2.将其导入您的代码中:
import "github.com/gin-gonic/gin"
3.(可选)导入net/http。例如,如果使用常量,则需要这样做http.StatusOK。
import "net/http"
- package main
-
- import (
- "net/http"
-
- "github.com/gin-gonic/gin"
- )
-
- func main() {
- // 1.创建路由
- r := gin.Default()
- // 2.绑定路由规则,执行的函数
- // gin.Context,封装了request和response
- r.GET("/", func(c *gin.Context) {
- c.String(http.StatusOK, "hello World for gindemo!")
- })
- // 3.监听端口,默认在8080
- // Run("里面不指定端口号默认为8080")
- r.Run(":9000")
- }

执行后浏览器打开,就可以发现已经建立一个简单的httpserver服务,并且返回hello world for gindemo!
gin 框架中采用的路由库是基于httprouter做的
gin支持Restful风格的API
即Representational State Transfer的缩写。直接翻译的意思是"表现层状态转化",是一种互联网应用程序的API设计理念:URL定位资源,用HTTP描述操作
1.获取文章 /blog/getXxx Get blog/Xxx
2.添加 /blog/addXxx POST blog/Xxx
3.修改 /blog/updateXxx PUT blog/Xxx
4.删除 /blog/delXxxx DELETE blog/Xxx