server.go 9.1 KB

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