server.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. package rest
  2. import (
  3. "crypto/tls"
  4. "log"
  5. "net/http"
  6. "path"
  7. "time"
  8. "github.com/zeromicro/go-zero/core/logx"
  9. "github.com/zeromicro/go-zero/rest/chain"
  10. "github.com/zeromicro/go-zero/rest/handler"
  11. "github.com/zeromicro/go-zero/rest/httpx"
  12. "github.com/zeromicro/go-zero/rest/internal/cors"
  13. "github.com/zeromicro/go-zero/rest/router"
  14. )
  15. type (
  16. // RunOption defines the method to customize a Server.
  17. RunOption func(*Server)
  18. // A Server is a http server.
  19. Server struct {
  20. ngin *engine
  21. router httpx.Router
  22. }
  23. )
  24. // MustNewServer returns a server with given config of c and options defined in opts.
  25. // Be aware that later RunOption might overwrite previous one that write the same option.
  26. // The process will exit if error occurs.
  27. func MustNewServer(c RestConf, opts ...RunOption) *Server {
  28. server, err := NewServer(c, opts...)
  29. if err != nil {
  30. log.Fatal(err)
  31. }
  32. return server
  33. }
  34. // NewServer returns a server with given config of c and options defined in opts.
  35. // Be aware that later RunOption might overwrite previous one that write the same option.
  36. func NewServer(c RestConf, opts ...RunOption) (*Server, error) {
  37. if err := c.SetUp(); err != nil {
  38. return nil, err
  39. }
  40. server := &Server{
  41. ngin: newEngine(c),
  42. router: router.NewRouter(),
  43. }
  44. opts = append([]RunOption{WithNotFoundHandler(nil)}, opts...)
  45. for _, opt := range opts {
  46. opt(server)
  47. }
  48. return server, nil
  49. }
  50. // AddRoutes add given routes into the Server.
  51. func (s *Server) AddRoutes(rs []Route, opts ...RouteOption) {
  52. r := featuredRoutes{
  53. routes: rs,
  54. }
  55. for _, opt := range opts {
  56. opt(&r)
  57. }
  58. s.ngin.addRoutes(r)
  59. }
  60. // AddRoute adds given route into the Server.
  61. func (s *Server) AddRoute(r Route, opts ...RouteOption) {
  62. s.AddRoutes([]Route{r}, opts...)
  63. }
  64. // PrintRoutes prints the added routes to stdout.
  65. func (s *Server) PrintRoutes() {
  66. s.ngin.print()
  67. }
  68. // Routes returns the HTTP routers that registered in the server.
  69. func (s *Server) Routes() []Route {
  70. var routes []Route
  71. for _, r := range s.ngin.routes {
  72. routes = append(routes, r.routes...)
  73. }
  74. return routes
  75. }
  76. // ServeHTTP is for test purpose, allow developer to do a unit test with
  77. // all defined router without starting an HTTP Server.
  78. //
  79. // For example:
  80. //
  81. // server := MustNewServer(...)
  82. // server.addRoute(...) // router a
  83. // server.addRoute(...) // router b
  84. // server.addRoute(...) // router c
  85. //
  86. // r, _ := http.NewRequest(...)
  87. // w := httptest.NewRecorder(...)
  88. // server.ServeHTTP(w, r)
  89. // // verify the response
  90. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  91. s.ngin.bindRoutes(s.router)
  92. s.router.ServeHTTP(w, r)
  93. }
  94. // Start starts the Server.
  95. // Graceful shutdown is enabled by default.
  96. // Use proc.SetTimeToForceQuit to customize the graceful shutdown period.
  97. func (s *Server) Start() {
  98. handleError(s.ngin.start(s.router))
  99. }
  100. // Stop stops the Server.
  101. func (s *Server) Stop() {
  102. logx.Close()
  103. }
  104. // Use adds the given middleware in the Server.
  105. func (s *Server) Use(middleware Middleware) {
  106. s.ngin.use(middleware)
  107. }
  108. // ToMiddleware converts the given handler to a Middleware.
  109. func ToMiddleware(handler func(next http.Handler) http.Handler) Middleware {
  110. return func(handle http.HandlerFunc) http.HandlerFunc {
  111. return handler(handle).ServeHTTP
  112. }
  113. }
  114. // WithChain returns a RunOption that uses the given chain to replace the default chain.
  115. // JWT auth middleware and the middlewares that added by svr.Use() will be appended.
  116. func WithChain(chn chain.Chain) RunOption {
  117. return func(svr *Server) {
  118. svr.ngin.chain = chn
  119. }
  120. }
  121. // WithCors returns a func to enable CORS for given origin, or default to all origins (*).
  122. func WithCors(origin ...string) RunOption {
  123. return func(server *Server) {
  124. server.router.SetNotAllowedHandler(cors.NotAllowedHandler(nil, origin...))
  125. server.router = newCorsRouter(server.router, nil, origin...)
  126. }
  127. }
  128. // WithCustomCors returns a func to enable CORS for given origin, or default to all origins (*),
  129. // fn lets caller customizing the response.
  130. func WithCustomCors(middlewareFn func(header http.Header), notAllowedFn func(http.ResponseWriter),
  131. origin ...string) RunOption {
  132. return func(server *Server) {
  133. server.router.SetNotAllowedHandler(cors.NotAllowedHandler(notAllowedFn, origin...))
  134. server.router = newCorsRouter(server.router, middlewareFn, origin...)
  135. }
  136. }
  137. // WithJwt returns a func to enable jwt authentication in given route.
  138. func WithJwt(secret string) RouteOption {
  139. return func(r *featuredRoutes) {
  140. validateSecret(secret)
  141. r.jwt.enabled = true
  142. r.jwt.secret = secret
  143. }
  144. }
  145. // WithJwtTransition returns a func to enable jwt authentication as well as jwt secret transition.
  146. // Which means old and new jwt secrets work together for a period.
  147. func WithJwtTransition(secret, prevSecret string) RouteOption {
  148. return func(r *featuredRoutes) {
  149. // why not validate prevSecret, because prevSecret is an already used one,
  150. // even it not meet our requirement, we still need to allow the transition.
  151. validateSecret(secret)
  152. r.jwt.enabled = true
  153. r.jwt.secret = secret
  154. r.jwt.prevSecret = prevSecret
  155. }
  156. }
  157. // WithMaxBytes returns a RouteOption to set maxBytes with the given value.
  158. func WithMaxBytes(maxBytes int64) RouteOption {
  159. return func(r *featuredRoutes) {
  160. r.maxBytes = maxBytes
  161. }
  162. }
  163. // WithMiddlewares adds given middlewares to given routes.
  164. func WithMiddlewares(ms []Middleware, rs ...Route) []Route {
  165. for i := len(ms) - 1; i >= 0; i-- {
  166. rs = WithMiddleware(ms[i], rs...)
  167. }
  168. return rs
  169. }
  170. // WithMiddleware adds given middleware to given route.
  171. func WithMiddleware(middleware Middleware, rs ...Route) []Route {
  172. routes := make([]Route, len(rs))
  173. for i := range rs {
  174. route := rs[i]
  175. routes[i] = Route{
  176. Method: route.Method,
  177. Path: route.Path,
  178. Handler: middleware(route.Handler),
  179. }
  180. }
  181. return routes
  182. }
  183. // WithNotFoundHandler returns a RunOption with not found handler set to given handler.
  184. func WithNotFoundHandler(handler http.Handler) RunOption {
  185. return func(server *Server) {
  186. notFoundHandler := server.ngin.notFoundHandler(handler)
  187. server.router.SetNotFoundHandler(notFoundHandler)
  188. }
  189. }
  190. // WithNotAllowedHandler returns a RunOption with not allowed handler set to given handler.
  191. func WithNotAllowedHandler(handler http.Handler) RunOption {
  192. return func(server *Server) {
  193. server.router.SetNotAllowedHandler(handler)
  194. }
  195. }
  196. // WithPrefix adds group as a prefix to the route paths.
  197. func WithPrefix(group string) RouteOption {
  198. return func(r *featuredRoutes) {
  199. var routes []Route
  200. for _, rt := range r.routes {
  201. p := path.Join(group, rt.Path)
  202. routes = append(routes, Route{
  203. Method: rt.Method,
  204. Path: p,
  205. Handler: rt.Handler,
  206. })
  207. }
  208. r.routes = routes
  209. }
  210. }
  211. // WithPriority returns a RunOption with priority.
  212. func WithPriority() RouteOption {
  213. return func(r *featuredRoutes) {
  214. r.priority = true
  215. }
  216. }
  217. // WithRouter returns a RunOption that make server run with given router.
  218. func WithRouter(router httpx.Router) RunOption {
  219. return func(server *Server) {
  220. server.router = router
  221. }
  222. }
  223. // WithSignature returns a RouteOption to enable signature verification.
  224. func WithSignature(signature SignatureConf) RouteOption {
  225. return func(r *featuredRoutes) {
  226. r.signature.enabled = true
  227. r.signature.Strict = signature.Strict
  228. r.signature.Expiry = signature.Expiry
  229. r.signature.PrivateKeys = signature.PrivateKeys
  230. }
  231. }
  232. // WithTimeout returns a RouteOption to set timeout with given value.
  233. func WithTimeout(timeout time.Duration) RouteOption {
  234. return func(r *featuredRoutes) {
  235. r.timeout = timeout
  236. }
  237. }
  238. // WithTLSConfig returns a RunOption that with given tls config.
  239. func WithTLSConfig(cfg *tls.Config) RunOption {
  240. return func(svr *Server) {
  241. svr.ngin.setTlsConfig(cfg)
  242. }
  243. }
  244. // WithUnauthorizedCallback returns a RunOption that with given unauthorized callback set.
  245. func WithUnauthorizedCallback(callback handler.UnauthorizedCallback) RunOption {
  246. return func(svr *Server) {
  247. svr.ngin.setUnauthorizedCallback(callback)
  248. }
  249. }
  250. // WithUnsignedCallback returns a RunOption that with given unsigned callback set.
  251. func WithUnsignedCallback(callback handler.UnsignedCallback) RunOption {
  252. return func(svr *Server) {
  253. svr.ngin.setUnsignedCallback(callback)
  254. }
  255. }
  256. func handleError(err error) {
  257. // ErrServerClosed means the server is closed manually
  258. if err == nil || err == http.ErrServerClosed {
  259. return
  260. }
  261. logx.Error(err)
  262. panic(err)
  263. }
  264. func validateSecret(secret string) {
  265. if len(secret) < 8 {
  266. panic("secret's length can't be less than 8")
  267. }
  268. }
  269. type corsRouter struct {
  270. httpx.Router
  271. middleware Middleware
  272. }
  273. func newCorsRouter(router httpx.Router, headerFn func(http.Header), origins ...string) httpx.Router {
  274. return &corsRouter{
  275. Router: router,
  276. middleware: cors.Middleware(headerFn, origins...),
  277. }
  278. }
  279. func (c *corsRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  280. c.middleware(c.Router.ServeHTTP)(w, r)
  281. }