| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- package htp
- import (
- "encoding/json"
- "net/http"
- "os"
- "testing"
- "time"
- "github.com/gin-gonic/gin"
- )
- 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)
- }
|