Gin框架介绍
和beego几乎同时出品的go语言web框架、性能比较好、使用起来很简单了。到2023年, 即便java/php为首的web开发需求已经相当萧条甚至被废弃的时间段里, go的gin框架依然还算流行。
gin的官网:https://gin-gonic.com/zh-cn
Gin Github地址:https://github.com/gin-gonic/gin
Gin环境搭建
要安装Gin软件包,需要先安装Go并设置Go工作区
下载并安装gin:
$ go get -u github.com/gin-gonic/gin
将gin引入到代码中:
import "github.com/gin-gonic/gin"
(可选)如果使用诸如http.StatusOK之类的常量,则需要引入net/http包:
import "net/http"
新建main.go配置路由
gin框架的hello world
1)确保已经安装go环境(goroot gopath配置)
2)(需要翻墙)
go get gopkg.in/gin-goninc/gin.v1
git clone https://github.com/gin-gonic/gin.git //(会有一个gin文件夹)
不翻墙这种方式下载的文件不完整,需要下载golang、gin-gonic、gin-contrib、ugorji 这四个包放到github.com文件夹里,同时还依赖于gopkg.in (包含go-playground、yaml.v2)这个包,放在path目录src下
下载后需要将gin拷贝到gopath下面src/github.com/gin-gonic/gin
或者通过翻墙的方式:
go get github.com/gin-gonic/gin.git
3)运行http://localhost:8080实现hello world——main.go
package main import ( "net/http" "github.com/gin-gonic/gin" ) func main (){ router := gin.Default() router.GET("/", func(context *gin.Context){ context.String(http.StatusOK,"hello world") }) router.Run() // 默认是8080端口 }
4)更改端口:router.Run("/:3333")
注意点:
1)gin需要翻墙
go get github.com/gin-gonic/gin
2)把课程对应的包,拷贝到gopath对应的src 和 github.com文件夹里面
go语言/gin/src/
--src
--github.com
--gin-contrib
--gin-gonic
--golang
--ugorji
---gopkg.in