server.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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(nil, s.router))
  102. }
  103. func (s *Server) StartAsGoRoutine() *http.Server {
  104. ch := make(chan *http.Server, 1)
  105. go func() {
  106. defer func() {
  107. recover()
  108. }()
  109. handleError(s.ngin.start(ch, s.router))
  110. }()
  111. return <-ch
  112. }
  113. // StartWithOpts starts the Server.
  114. // Graceful shutdown is enabled by default.
  115. // Use proc.SetTimeToForceQuit to customize the graceful shutdown period.
  116. func (s *Server) StartWithOpts(opts ...StartOption) {
  117. handleError(s.ngin.start(nil, s.router, opts...))
  118. }
  119. func (s *Server) StartAsGoRoutineWithOpts(opts ...StartOption) *http.Server {
  120. ch := make(chan *http.Server, 1)
  121. go func() {
  122. defer func() {
  123. recover()
  124. }()
  125. handleError(s.ngin.start(ch, s.router, opts...))
  126. }()
  127. return <-ch
  128. }
  129. // Stop stops the Server.
  130. func (s *Server) Stop() {
  131. logx.Close()
  132. }
  133. // Use adds the given middleware in the Server.
  134. func (s *Server) Use(middleware Middleware) {
  135. s.ngin.use(middleware)
  136. }
  137. // ToMiddleware converts the given handler to a Middleware.
  138. func ToMiddleware(handler func(next http.Handler) http.Handler) Middleware {
  139. return func(handle http.HandlerFunc) http.HandlerFunc {
  140. return handler(handle).ServeHTTP
  141. }
  142. }
  143. // WithChain returns a RunOption that uses the given chain to replace the default chain.
  144. // JWT auth middleware and the middlewares that added by svr.Use() will be appended.
  145. func WithChain(chn chain.Chain) RunOption {
  146. return func(svr *Server) {
  147. svr.ngin.chain = chn
  148. }
  149. }
  150. // WithCors returns a func to enable CORS for given origin, or default to all origins (*).
  151. func WithCors(origin ...string) RunOption {
  152. return func(server *Server) {
  153. server.router.SetNotAllowedHandler(cors.NotAllowedHandler(nil, origin...))
  154. server.router = newCorsRouter(server.router, nil, origin...)
  155. }
  156. }
  157. // WithCustomCors returns a func to enable CORS for given origin, or default to all origins (*),
  158. // fn lets caller customizing the response.
  159. func WithCustomCors(middlewareFn func(header http.Header), notAllowedFn func(http.ResponseWriter),
  160. origin ...string) RunOption {
  161. return func(server *Server) {
  162. server.router.SetNotAllowedHandler(cors.NotAllowedHandler(notAllowedFn, origin...))
  163. server.router = newCorsRouter(server.router, middlewareFn, origin...)
  164. }
  165. }
  166. // WithJwt returns a func to enable jwt authentication in given route.
  167. func WithJwt(secret string) RouteOption {
  168. return func(r *featuredRoutes) {
  169. validateSecret(secret)
  170. r.jwt.enabled = true
  171. r.jwt.secret = secret
  172. }
  173. }
  174. // WithJwtTransition returns a func to enable jwt authentication as well as jwt secret transition.
  175. // Which means old and new jwt secrets work together for a period.
  176. func WithJwtTransition(secret, prevSecret string) RouteOption {
  177. return func(r *featuredRoutes) {
  178. // why not validate prevSecret, because prevSecret is an already used one,
  179. // even it not meet our requirement, we still need to allow the transition.
  180. validateSecret(secret)
  181. r.jwt.enabled = true
  182. r.jwt.secret = secret
  183. r.jwt.prevSecret = prevSecret
  184. }
  185. }
  186. // WithMaxBytes returns a RouteOption to set maxBytes with the given value.
  187. func WithMaxBytes(maxBytes int64) RouteOption {
  188. return func(r *featuredRoutes) {
  189. r.maxBytes = maxBytes
  190. }
  191. }
  192. // WithMiddlewares adds given middlewares to given routes.
  193. func WithMiddlewares(ms []Middleware, rs ...Route) []Route {
  194. for i := len(ms) - 1; i >= 0; i-- {
  195. rs = WithMiddleware(ms[i], rs...)
  196. }
  197. return rs
  198. }
  199. // WithMiddleware adds given middleware to given route.
  200. func WithMiddleware(middleware Middleware, rs ...Route) []Route {
  201. routes := make([]Route, len(rs))
  202. for i := range rs {
  203. route := rs[i]
  204. routes[i] = Route{
  205. Method: route.Method,
  206. Path: route.Path,
  207. Handler: middleware(route.Handler),
  208. }
  209. }
  210. return routes
  211. }
  212. // WithNotFoundHandler returns a RunOption with not found handler set to given handler.
  213. func WithNotFoundHandler(handler http.Handler) RunOption {
  214. return func(server *Server) {
  215. notFoundHandler := server.ngin.notFoundHandler(handler)
  216. server.router.SetNotFoundHandler(notFoundHandler)
  217. }
  218. }
  219. // WithNotAllowedHandler returns a RunOption with not allowed handler set to given handler.
  220. func WithNotAllowedHandler(handler http.Handler) RunOption {
  221. return func(server *Server) {
  222. server.router.SetNotAllowedHandler(handler)
  223. }
  224. }
  225. func WithOptionsHandler(handler http.Handler) RunOption {
  226. return func(server *Server) {
  227. server.router.SetOptionsHandler(handler)
  228. }
  229. }
  230. func WithGlobalMiddleware(middleware httpx.MiddlewareFunc) RunOption {
  231. return func(server *Server) {
  232. server.router.SetMiddleware(middleware)
  233. }
  234. }
  235. // WithPrefix adds group as a prefix to the route paths.
  236. func WithPrefix(group string) RouteOption {
  237. return func(r *featuredRoutes) {
  238. var routes []Route
  239. for _, rt := range r.routes {
  240. p := path.Join(group, rt.Path)
  241. routes = append(routes, Route{
  242. Method: rt.Method,
  243. Path: p,
  244. Handler: rt.Handler,
  245. })
  246. }
  247. r.routes = routes
  248. }
  249. }
  250. // WithPriority returns a RunOption with priority.
  251. func WithPriority() RouteOption {
  252. return func(r *featuredRoutes) {
  253. r.priority = true
  254. }
  255. }
  256. // WithRouter returns a RunOption that make server run with given router.
  257. func WithRouter(router httpx.Router) RunOption {
  258. return func(server *Server) {
  259. server.router = router
  260. }
  261. }
  262. // WithSignature returns a RouteOption to enable signature verification.
  263. func WithSignature(signature SignatureConf) RouteOption {
  264. return func(r *featuredRoutes) {
  265. r.signature.enabled = true
  266. r.signature.Strict = signature.Strict
  267. r.signature.Expiry = signature.Expiry
  268. r.signature.PrivateKeys = signature.PrivateKeys
  269. }
  270. }
  271. // WithTimeout returns a RouteOption to set timeout with given value.
  272. func WithTimeout(timeout time.Duration) RouteOption {
  273. return func(r *featuredRoutes) {
  274. r.timeout = timeout
  275. }
  276. }
  277. // WithTLSConfig returns a RunOption that with given tls config.
  278. func WithTLSConfig(cfg *tls.Config) RunOption {
  279. return func(svr *Server) {
  280. svr.ngin.setTlsConfig(cfg)
  281. }
  282. }
  283. // WithUnauthorizedCallback returns a RunOption that with given unauthorized callback set.
  284. func WithUnauthorizedCallback(callback handler.UnauthorizedCallback) RunOption {
  285. return func(svr *Server) {
  286. svr.ngin.setUnauthorizedCallback(callback)
  287. }
  288. }
  289. // WithUnsignedCallback returns a RunOption that with given unsigned callback set.
  290. func WithUnsignedCallback(callback handler.UnsignedCallback) RunOption {
  291. return func(svr *Server) {
  292. svr.ngin.setUnsignedCallback(callback)
  293. }
  294. }
  295. func handleError(err error) {
  296. // ErrServerClosed means the server is closed manually
  297. if err == nil || errors.Is(err, http.ErrServerClosed) {
  298. return
  299. }
  300. logx.Error(err)
  301. panic(err)
  302. }
  303. func validateSecret(secret string) {
  304. if len(secret) < 8 {
  305. panic("secret's length can't be less than 8")
  306. }
  307. }
  308. type corsRouter struct {
  309. httpx.Router
  310. middleware Middleware
  311. }
  312. func newCorsRouter(router httpx.Router, headerFn func(http.Header), origins ...string) httpx.Router {
  313. return &corsRouter{
  314. Router: router,
  315. middleware: cors.Middleware(headerFn, origins...),
  316. }
  317. }
  318. func (c *corsRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  319. c.middleware(c.Router.ServeHTTP)(w, r)
  320. }