server_test.go 7.4 KB

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