golang 原生 http 库已经可以很方便地实现一个 http server 了,但对于复杂的 web 服务来说,路由解析,请求参数解析,对象返回等等,原生 api 就显得有些不太够用了,而 gin 是一个功能完备,性能很高的 web 网络框架,特别适合 web api 的开发
hello world
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.New()
r.GET("/ping", func(c *gin.Context) {
c.String(200, "hello world")
})
r.Run() // listen and serve on 0.0.0.0:8080
}
如这个 hello world
程序所示 gin 所有的业务逻辑都在 func(c *gin.Context)
函数中实现,请求和返回都通过这个 gin.Context 传递
请求参数解析
gin 提供了丰富的请求参数获取方式
(c *Context) Query(key string) string // 获取 GET 参数
(c *Context) QueryArray(key string) []string // 获取 GET 参数数组
(c *Context) DefaultQuery(key, defaultValue string)