Hello World
使用Gin实现Hello world非常简单,创建一个router,然后使用其Run的方法:
import
(
"gopkg.in/gin-gonic/gin.v1"
"net/http"
)
func
main
()
{
router := gin.Default()
router.GET(
"/"
, func(c *gin.Context) {
c.String(http.StatusOK,
"Hello World"
)
})
router.Run(
":8000"
)
}
简单几行代码,就能实现一个web服务。使用gin的Default方法创建一个路由handler。然后通过HTTP方法绑定路由规则和路由函数。不同于net/http库的路由函数,gin进行了封装,把request和response都封装到gin.Context的上下文环境。最后是启动路由的Run方法监听端口。麻雀虽小,五脏俱全。当然,除了GET方法,gin也支持POST,PUT,DELETE,OPTION等常用的restful方法。