Gin框架入门系列1:基本框架
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Gin框架入门系列1:基本框架相关的知识,希望对你有一定的参考价值。
1、安装go get -u github.com/gin-gonic/gin
2、简单实现helloworld 实例
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
// 创建路由
router.GET("/index", func(c *gin.Context) {
c.String(http.StatusOK,"hello world")
})
//监听服务,默认:8080
router.Run(":9090")
}
上面的例子中,我们注册了一个GET 方法访问 "/index" 的路由,在浏览器中访问http://localhost:9090/index
3、单元测试
基于assert 断言,判断http api 返回的状态码跟内容是否与预期一致
// main.go
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func SetupRouter() *gin.Engine{
router := gin.Default()
router.GET("/ping", func(c *gin.Context) {
c.String(http.StatusOK,"pong")
})
return router
}
func main() {
r := SetupRouter()
r.Run(":9090")
}
// index_test.go
package main
import (
"gopkg.in/go-playground/assert.v1"
"net/http"
"net/http/httptest"
"testing"
)
func TestIndexGetRouter(t *testing.T){
router := SetupRouter()
w := httptest.NewRecorder()
req ,_ := http.NewRequest(http.MethodGet,"/ping",nil)
router.ServeHTTP(w,req)
assert.Equal(t,http.StatusOK,w.Code)
assert.Equal(t,"pong",w.Body.String())
}
[GIN-debug] GET /ping --> awesomeProject.SetupRouter.func1 (3 handlers)
[GIN] 2020/02/26 - 22:25:22 | 200 | 0s | | GET /ping
--- PASS: TestIndexGetRouter (0.22s)
PASS
4、gin router
gin router 的三种启动方式
(1) router.Run()
(2) http.ListenAndServe()
func main() {
router := gin.Default()
http.ListenAndServe(":8080", router)
}
(3) 自定义http服务器
func main() {
router := gin.Default()
s := &http.Server{
Addr: ":8080",
Handler: router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
s.ListenAndServe()
}
以上是关于Gin框架入门系列1:基本框架的主要内容,如果未能解决你的问题,请参考以下文章