一. Gin
Gin是Golang的一个web框架,封装优雅API友好,源码注释比较明确。借助Gin框架开发web服务,不仅可以省去很多常用的封装带来的时间,也有助于团队的编码风格和形成规范。
详细参考Github项目地址 https://github.com/gin-gonic/gin
- 安装Gin
go get -u github.com/gin-gonic/gin
- 使用Gin
import "github.com/gin-gonic/gin"
二. Hello World
使用Gin只需要几行代码就可以轻松实现一个web服务,下面我们看一个简单的例子实现HTTP请求打印“Hello World”。
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main(){
router := gin.Default()
router.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Hello World")
})
router.Run(":8000")
}
- router := gin.Default() 获取默认的Engine
- router.GET("/", func(c *gin.Context) HTTP方法绑定路由规则以及相应的处理方法
- router.Run(":8000") 开启服务监听8000端口
三. 分组路由
Gin提供了分组路由的功能,能够让代码更加模块化。
v1 := router.Group("/v1")
v1.GET("/login", func(c *gin.Context) {
c.String(http.StatusOK, "v1 login")
})
v2 := router.Group("/v2")
v2.GET("/login", func(c *gin.Context) {
c.String(http.StatusOK, "v2 login")
})