server_test.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. package rest
  2. import (
  3. "crypto/tls"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "net/http/httptest"
  8. "testing"
  9. "time"
  10. "github.com/stretchr/testify/assert"
  11. "github.com/tal-tech/go-zero/core/conf"
  12. "github.com/tal-tech/go-zero/rest/httpx"
  13. "github.com/tal-tech/go-zero/rest/router"
  14. )
  15. func TestNewServer(t *testing.T) {
  16. const configYaml = `
  17. Name: foo
  18. Port: 54321
  19. `
  20. var cnf RestConf
  21. assert.Nil(t, conf.LoadConfigFromYamlBytes([]byte(configYaml), &cnf))
  22. failStart := func(server *Server) {
  23. server.opts.start = func(e *engine) error {
  24. return http.ErrServerClosed
  25. }
  26. }
  27. tests := []struct {
  28. c RestConf
  29. opts []RunOption
  30. fail bool
  31. }{
  32. {
  33. c: RestConf{},
  34. opts: []RunOption{failStart},
  35. fail: true,
  36. },
  37. {
  38. c: cnf,
  39. opts: []RunOption{failStart},
  40. },
  41. {
  42. c: cnf,
  43. opts: []RunOption{WithNotAllowedHandler(nil), failStart},
  44. },
  45. {
  46. c: cnf,
  47. opts: []RunOption{WithNotFoundHandler(nil), failStart},
  48. },
  49. {
  50. c: cnf,
  51. opts: []RunOption{WithUnauthorizedCallback(nil), failStart},
  52. },
  53. {
  54. c: cnf,
  55. opts: []RunOption{WithUnsignedCallback(nil), failStart},
  56. },
  57. }
  58. for _, test := range tests {
  59. srv, err := NewServer(test.c, test.opts...)
  60. if test.fail {
  61. assert.NotNil(t, err)
  62. }
  63. if err != nil {
  64. continue
  65. }
  66. srv.Use(ToMiddleware(func(next http.Handler) http.Handler {
  67. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  68. next.ServeHTTP(w, r)
  69. })
  70. }))
  71. srv.AddRoute(Route{
  72. Method: http.MethodGet,
  73. Path: "/",
  74. Handler: nil,
  75. }, WithJwt("thesecret"), WithSignature(SignatureConf{}),
  76. WithJwtTransition("preivous", "thenewone"))
  77. srv.Start()
  78. srv.Stop()
  79. }
  80. }
  81. func TestWithMiddleware(t *testing.T) {
  82. m := make(map[string]string)
  83. rt := router.NewRouter()
  84. handler := func(w http.ResponseWriter, r *http.Request) {
  85. var v struct {
  86. Nickname string `form:"nickname"`
  87. Zipcode int64 `form:"zipcode"`
  88. }
  89. err := httpx.Parse(r, &v)
  90. assert.Nil(t, err)
  91. _, err = io.WriteString(w, fmt.Sprintf("%s:%d", v.Nickname, v.Zipcode))
  92. assert.Nil(t, err)
  93. }
  94. rs := WithMiddleware(func(next http.HandlerFunc) http.HandlerFunc {
  95. return func(w http.ResponseWriter, r *http.Request) {
  96. var v struct {
  97. Name string `path:"name"`
  98. Year string `path:"year"`
  99. }
  100. assert.Nil(t, httpx.ParsePath(r, &v))
  101. m[v.Name] = v.Year
  102. next.ServeHTTP(w, r)
  103. }
  104. }, Route{
  105. Method: http.MethodGet,
  106. Path: "/first/:name/:year",
  107. Handler: handler,
  108. }, Route{
  109. Method: http.MethodGet,
  110. Path: "/second/:name/:year",
  111. Handler: handler,
  112. })
  113. urls := []string{
  114. "http://hello.com/first/kevin/2017?nickname=whatever&zipcode=200000",
  115. "http://hello.com/second/wan/2020?nickname=whatever&zipcode=200000",
  116. }
  117. for _, route := range rs {
  118. assert.Nil(t, rt.Handle(route.Method, route.Path, route.Handler))
  119. }
  120. for _, url := range urls {
  121. r, err := http.NewRequest(http.MethodGet, url, nil)
  122. assert.Nil(t, err)
  123. rr := httptest.NewRecorder()
  124. rt.ServeHTTP(rr, r)
  125. assert.Equal(t, "whatever:200000", rr.Body.String())
  126. }
  127. assert.EqualValues(t, map[string]string{
  128. "kevin": "2017",
  129. "wan": "2020",
  130. }, m)
  131. }
  132. func TestMultiMiddlewares(t *testing.T) {
  133. m := make(map[string]string)
  134. rt := router.NewRouter()
  135. handler := func(w http.ResponseWriter, r *http.Request) {
  136. var v struct {
  137. Nickname string `form:"nickname"`
  138. Zipcode int64 `form:"zipcode"`
  139. }
  140. err := httpx.Parse(r, &v)
  141. assert.Nil(t, err)
  142. _, err = io.WriteString(w, fmt.Sprintf("%s:%s", v.Nickname, m[v.Nickname]))
  143. assert.Nil(t, err)
  144. }
  145. rs := WithMiddlewares([]Middleware{
  146. func(next http.HandlerFunc) http.HandlerFunc {
  147. return func(w http.ResponseWriter, r *http.Request) {
  148. var v struct {
  149. Name string `path:"name"`
  150. Year string `path:"year"`
  151. }
  152. assert.Nil(t, httpx.ParsePath(r, &v))
  153. m[v.Name] = v.Year
  154. next.ServeHTTP(w, r)
  155. }
  156. },
  157. func(next http.HandlerFunc) http.HandlerFunc {
  158. return func(w http.ResponseWriter, r *http.Request) {
  159. var v struct {
  160. Name string `form:"nickname"`
  161. Zipcode string `form:"zipcode"`
  162. }
  163. assert.Nil(t, httpx.ParseForm(r, &v))
  164. assert.NotEmpty(t, m)
  165. m[v.Name] = v.Zipcode + v.Zipcode
  166. next.ServeHTTP(w, r)
  167. }
  168. },
  169. }, Route{
  170. Method: http.MethodGet,
  171. Path: "/first/:name/:year",
  172. Handler: handler,
  173. }, Route{
  174. Method: http.MethodGet,
  175. Path: "/second/:name/:year",
  176. Handler: handler,
  177. })
  178. urls := []string{
  179. "http://hello.com/first/kevin/2017?nickname=whatever&zipcode=200000",
  180. "http://hello.com/second/wan/2020?nickname=whatever&zipcode=200000",
  181. }
  182. for _, route := range rs {
  183. assert.Nil(t, rt.Handle(route.Method, route.Path, route.Handler))
  184. }
  185. for _, url := range urls {
  186. r, err := http.NewRequest(http.MethodGet, url, nil)
  187. assert.Nil(t, err)
  188. rr := httptest.NewRecorder()
  189. rt.ServeHTTP(rr, r)
  190. assert.Equal(t, "whatever:200000200000", rr.Body.String())
  191. }
  192. assert.EqualValues(t, map[string]string{
  193. "kevin": "2017",
  194. "wan": "2020",
  195. "whatever": "200000200000",
  196. }, m)
  197. }
  198. func TestWithPrefix(t *testing.T) {
  199. fr := featuredRoutes{
  200. routes: []Route{
  201. {
  202. Path: "/hello",
  203. },
  204. {
  205. Path: "/world",
  206. },
  207. },
  208. }
  209. WithPrefix("/api")(&fr)
  210. var vals []string
  211. for _, r := range fr.routes {
  212. vals = append(vals, r.Path)
  213. }
  214. assert.EqualValues(t, []string{"/api/hello", "/api/world"}, vals)
  215. }
  216. func TestWithPriority(t *testing.T) {
  217. var fr featuredRoutes
  218. WithPriority()(&fr)
  219. assert.True(t, fr.priority)
  220. }
  221. func TestWithTimeout(t *testing.T) {
  222. var fr featuredRoutes
  223. WithTimeout(time.Hour)(&fr)
  224. assert.Equal(t, time.Hour, fr.timeout)
  225. }
  226. func TestWithTLSConfig(t *testing.T) {
  227. const configYaml = `
  228. Name: foo
  229. Port: 54321
  230. `
  231. var cnf RestConf
  232. assert.Nil(t, conf.LoadConfigFromYamlBytes([]byte(configYaml), &cnf))
  233. testConfig := &tls.Config{
  234. CipherSuites: []uint16{
  235. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  236. },
  237. }
  238. testCases := []struct {
  239. c RestConf
  240. opts []RunOption
  241. res *tls.Config
  242. }{
  243. {
  244. c: cnf,
  245. opts: []RunOption{WithTLSConfig(testConfig)},
  246. res: testConfig,
  247. },
  248. {
  249. c: cnf,
  250. opts: []RunOption{WithUnsignedCallback(nil)},
  251. res: nil,
  252. },
  253. }
  254. for _, testCase := range testCases {
  255. srv, err := NewServer(testCase.c, testCase.opts...)
  256. assert.Nil(t, err)
  257. assert.Equal(t, srv.ngin.tlsConfig, testCase.res)
  258. }
  259. }