server.go 9.0 KB

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