安装
go get -u github.com/gin-gonic/gin
引入包
import (
"github.com/gin-gonic/gin"
"net/http"
)
简单案例
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/helloworld", func(context *gin.Context) {
context.String(http.StatusOK, "hello %s", "gc")
})
r.Run(":8081") // 启动端口号
}
net/http 库中 http的状态码 常用 http.StatusOK, 也可以直接返回200,http响应状态吗
路由
简单案例
func main() {
route := gin.Default()
route.GET("/:name/:id", func(c *gin.Context) {
var person Person
if err := c.ShouldBindUri(&person); err != nil {
c.JSON(400, gin.H{"msg": err})
return
}
c.JSON(200, gin.H{"name": person.Name, "uuid": person.ID})
})
route.Run(":8088")
}
简单封装 router.go
// router.go
func SetupRouter() *gin.Engine {
r := gin.Default()
// 开启跨域
r.Use(Cors())
// 静态资源配置
r.Static("/static/image", config.ImageDir)
r.GET(`/index`, controller.Index)
r.GET(`/getAdmin`, controller.Get)
return r
}
// main.go
func main() {
// web服务启动后开启定时任务, 用于定期更新资源
// 开启路由监听
r := router.SetupRouter()
_ = r.Run(fmt.Sprintf(":%d", 8080))
}
设置静态文件目录
Static("访问地址","目录地址")
***注意: gin中 目录地址如果使用相对路径,相对路径地址为项目根目录的相对
**主要参数
GET get请求
POST post 请求
PUT put请求
…
路径参数
func main() {
r := gin.Default()
r.GET("/user/:name/*action", func(c *gin.Context) {
name := c.Param("name")
action := c.Param("action")
//截取/
action = strings.Trim(action, "/")
c.String(http.StatusOK, name+" is "+action)
})
//默认为监听8080端口
r.Run(":8000")
}
0