http_binding_test.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package api_binding
  2. import (
  3. "git.sxidc.com/go-tools/api_binding/http_binding"
  4. "git.sxidc.com/go-tools/api_binding/http_binding/binding_context"
  5. "git.sxidc.com/go-tools/api_binding/http_binding/response"
  6. "github.com/goccy/go-json"
  7. "io"
  8. "net/http"
  9. "testing"
  10. )
  11. func TestHttpBinding(t *testing.T) {
  12. http_binding.Init("test", "10000")
  13. defer http_binding.Destroy()
  14. testBinding := http_binding.NewBinding("test")
  15. http_binding.GetBind(testBinding, &http_binding.SimpleBindItem[any, map[string]interface{}]{
  16. Path: "/ping",
  17. ResponseFunc: response.SendMapResponse,
  18. BusinessFunc: func(c *binding_context.Context, inputModel any) (map[string]interface{}, error) {
  19. return map[string]interface{}{
  20. "result": "pong",
  21. }, nil
  22. },
  23. })
  24. resp, err := http.Get("http://localhost:10000/test/api/test/ping")
  25. if err != nil {
  26. t.Fatal(err)
  27. }
  28. if resp.StatusCode != http.StatusOK {
  29. t.Fatal("状态码错误")
  30. }
  31. body, err := io.ReadAll(resp.Body)
  32. if err != nil {
  33. t.Fatal(err)
  34. }
  35. defer func(Body io.ReadCloser) {
  36. err := Body.Close()
  37. if err != nil {
  38. t.Fatal(err)
  39. }
  40. }(resp.Body)
  41. respMap := make(map[string]interface{})
  42. err = json.Unmarshal(body, &respMap)
  43. if err != nil {
  44. t.Fatal(err)
  45. }
  46. pong, ok := respMap["result"]
  47. if !ok {
  48. t.Fatal("响应错误")
  49. }
  50. if pong != "pong" {
  51. t.Fatal("响应错误")
  52. }
  53. }