| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- 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)
- }
|