server_test.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package rest
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "testing"
  8. "github.com/stretchr/testify/assert"
  9. "github.com/tal-tech/go-zero/rest/httpx"
  10. "github.com/tal-tech/go-zero/rest/router"
  11. )
  12. func TestWithMiddleware(t *testing.T) {
  13. m := make(map[string]string)
  14. router := router.NewPatRouter()
  15. handler := func(w http.ResponseWriter, r *http.Request) {
  16. var v struct {
  17. Nickname string `form:"nickname"`
  18. Zipcode int64 `form:"zipcode"`
  19. }
  20. err := httpx.Parse(r, &v)
  21. assert.Nil(t, err)
  22. _, err = io.WriteString(w, fmt.Sprintf("%s:%d", v.Nickname, v.Zipcode))
  23. assert.Nil(t, err)
  24. }
  25. rs := WithMiddleware(func(next http.HandlerFunc) http.HandlerFunc {
  26. return func(w http.ResponseWriter, r *http.Request) {
  27. var v struct {
  28. Name string `path:"name"`
  29. Year string `path:"year"`
  30. }
  31. assert.Nil(t, httpx.ParsePath(r, &v))
  32. m[v.Name] = v.Year
  33. next.ServeHTTP(w, r)
  34. }
  35. }, Route{
  36. Method: http.MethodGet,
  37. Path: "/first/:name/:year",
  38. Handler: handler,
  39. }, Route{
  40. Method: http.MethodGet,
  41. Path: "/second/:name/:year",
  42. Handler: handler,
  43. })
  44. urls := []string{
  45. "http://hello.com/first/kevin/2017?nickname=whatever&zipcode=200000",
  46. "http://hello.com/second/wan/2020?nickname=whatever&zipcode=200000",
  47. }
  48. for _, route := range rs {
  49. assert.Nil(t, router.Handle(route.Method, route.Path, route.Handler))
  50. }
  51. for _, url := range urls {
  52. r, err := http.NewRequest(http.MethodGet, url, nil)
  53. assert.Nil(t, err)
  54. rr := httptest.NewRecorder()
  55. router.ServeHTTP(rr, r)
  56. assert.Equal(t, "whatever:200000", rr.Body.String())
  57. }
  58. assert.EqualValues(t, map[string]string{
  59. "kevin": "2017",
  60. "wan": "2020",
  61. }, m)
  62. }