server_test.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package htp
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "os"
  6. "testing"
  7. "time"
  8. "github.com/gin-gonic/gin"
  9. )
  10. func setup() {
  11. }
  12. func tearDown() {
  13. }
  14. type JsonBody struct {
  15. Name string
  16. Age uint32
  17. }
  18. func TestNewGinServer(t *testing.T) {
  19. svr := NewGinServer("127.0.0.1:3008")
  20. err := svr.Start(func(e *gin.Engine) {
  21. e.POST("/mate", func(ctx *gin.Context) {
  22. reqp := &JsonBody{}
  23. err := ctx.ShouldBindJSON(&reqp)
  24. if nil != err {
  25. ctx.JSON(http.StatusBadRequest, gin.H{})
  26. return
  27. }
  28. t.Logf("name:%v, age:%v", reqp.Name, reqp.Age)
  29. ctx.JSON(http.StatusOK, gin.H{"ec": 0})
  30. })
  31. e.GET("/name", func(ctx *gin.Context) {
  32. ctx.JSON(http.StatusOK, gin.H{"ec": 0, "name": "hello"})
  33. })
  34. })
  35. if err != nil {
  36. t.Fatal(err)
  37. }
  38. defer svr.Stop()
  39. time.Sleep(2 * time.Second)
  40. clt := NewClient()
  41. // test client post here
  42. headers := map[string]string{
  43. "Content-Type": "application/json",
  44. }
  45. body := JsonBody{
  46. Name: "test",
  47. Age: 25,
  48. }
  49. bp, err := json.Marshal(&body)
  50. if err != nil {
  51. t.Fatal(err)
  52. }
  53. ret, err := clt.Post("http://127.0.0.1:3008/mate", headers, bp)
  54. if err != nil {
  55. t.Fatal(err)
  56. }
  57. t.Logf("%s", ret)
  58. // test client get again
  59. content, err := clt.Get("http://127.0.0.1:3008/name")
  60. if err != nil {
  61. t.Fatal(err)
  62. }
  63. t.Logf("%s", content)
  64. }
  65. func TestMain(m *testing.M) {
  66. setup()
  67. ec := m.Run()
  68. tearDown()
  69. os.Exit(ec)
  70. }