package htp import ( "encoding/json" "github.com/gin-gonic/gin" "net/http" "os" "testing" "time" ) func setup() { } func tearDown() { } type JsonBody struct { Name string Age uint32 } func TestNewGinServer(t *testing.T) { svr := NewGinServer("127.0.0.1:3008") err := svr.Start(func(e *gin.Engine) { e.POST("/mate", func(ctx *gin.Context) { reqp := &JsonBody{} err := ctx.ShouldBindJSON(&reqp) if nil != err { ctx.JSON(http.StatusBadRequest, gin.H{}) return } t.Logf("name:%v, age:%v", reqp.Name, reqp.Age) ctx.JSON(http.StatusOK, gin.H{"ec": 0}) }) e.GET("/name", func(ctx *gin.Context) { ctx.JSON(http.StatusOK, gin.H{"ec": 0, "name": "hello"}) }) }) if err != nil { t.Fatal(err) } defer svr.Stop() time.Sleep(2 * time.Second) clt := NewClient() // test client post here headers := map[string]string{ "Content-Type": "application/json", } body := JsonBody{ Name: "test", Age: 25, } bp, err := json.Marshal(&body) if err != nil { t.Fatal(err) } ret, err := clt.Post("http://127.0.0.1:3008/mate", headers, bp) if err != nil { t.Fatal(err) } t.Logf("%s", ret) // test client get again content, err := clt.Get("http://127.0.0.1:3008/name") if err != nil { t.Fatal(err) } t.Logf("%s", content) } func TestMain(m *testing.M) { setup() ec := m.Run() tearDown() os.Exit(ec) }