Gin框架入門系列1:基本框架

一、安裝git

go get -u github.com/gin-gonic/gin

二、簡單實現helloworld 實例github

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/indexapi

三、單元測試
基於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

四、gin router
gin router 的三種啓動方式
(1) router.Run()服務器

(2) http.ListenAndServe()ide

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()
}
相關文章
相關標籤/搜索