Gin是一个非常受欢迎的Golang Web框架,它是一个类似于martini但拥有更好性能的API框架, 由于使用了httprouter,速度提高了近40倍。 如果你是性能和高效的追求者, 你会爱上Gin。
下载并安装Gin:
go get -u github.com/gin-gonic/gin
gin hello world
使用gin编写一个接口也是非常简单
package main
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(":9000")
}
CopyErrorOK!
router:=gin.Default():这是默认的服务器。使用gin的Default方法创建一个路由Handler;- 然后通过Http方法绑定路由规则和路由函数。不同于
net/http库的路由函数,gin进行了封装,把request和response都封装到了gin.Context的上下文环境中。 - 最后启动路由的Run方法监听端口。还可以用
http.ListenAndServe(":9000", router),或者自定义Http服务器配置。