server.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. // Start starts the Server.
  77. // Graceful shutdown is enabled by default.
  78. // Use proc.SetTimeToForceQuit to customize the graceful shutdown period.
  79. func (s *Server) Start() {
  80. handleError(s.ngin.start(s.router))
  81. }
  82. // Stop stops the Server.
  83. func (s *Server) Stop() {
  84. logx.Close()
  85. }
  86. // Use adds the given middleware in the Server.
  87. func (s *Server) Use(middleware Middleware) {
  88. s.ngin.use(middleware)
  89. }
  90. // ToMiddleware converts the given handler to a Middleware.
  91. func ToMiddleware(handler func(next http.Handler) http.Handler) Middleware {
  92. return func(handle http.HandlerFunc) http.HandlerFunc {
  93. return handler(handle).ServeHTTP
  94. }
  95. }
  96. // WithChain returns a RunOption that uses the given chain to replace the default chain.
  97. // JWT auth middleware and the middlewares that added by svr.Use() will be appended.
  98. func WithChain(chn chain.Chain) RunOption {
  99. return func(svr *Server) {
  100. svr.ngin.chain = chn
  101. }
  102. }
  103. // WithCors returns a func to enable CORS for given origin, or default to all origins (*).
  104. func WithCors(origin ...string) RunOption {
  105. return func(server *Server) {
  106. server.router.SetNotAllowedHandler(cors.NotAllowedHandler(nil, origin...))
  107. server.router = newCorsRouter(server.router, nil, origin...)
  108. }
  109. }
  110. // WithCustomCors returns a func to enable CORS for given origin, or default to all origins (*),
  111. // fn lets caller customizing the response.
  112. func WithCustomCors(middlewareFn func(header http.Header), notAllowedFn func(http.ResponseWriter),
  113. origin ...string) RunOption {
  114. return func(server *Server) {
  115. server.router.SetNotAllowedHandler(cors.NotAllowedHandler(notAllowedFn, origin...))
  116. server.router = newCorsRouter(server.router, middlewareFn, origin...)
  117. }
  118. }
  119. // WithJwt returns a func to enable jwt authentication in given route.
  120. func WithJwt(secret string) RouteOption {
  121. return func(r *featuredRoutes) {
  122. validateSecret(secret)
  123. r.jwt.enabled = true
  124. r.jwt.secret = secret
  125. }
  126. }
  127. // WithJwtTransition returns a func to enable jwt authentication as well as jwt secret transition.
  128. // Which means old and new jwt secrets work together for a period.
  129. func WithJwtTransition(secret, prevSecret string) RouteOption {
  130. return func(r *featuredRoutes) {
  131. // why not validate prevSecret, because prevSecret is an already used one,
  132. // even it not meet our requirement, we still need to allow the transition.
  133. validateSecret(secret)
  134. r.jwt.enabled = true
  135. r.jwt.secret = secret
  136. r.jwt.prevSecret = prevSecret
  137. }
  138. }
  139. // WithMaxBytes returns a RouteOption to set maxBytes with the given value.
  140. func WithMaxBytes(maxBytes int64) RouteOption {
  141. return func(r *featuredRoutes) {
  142. r.maxBytes = maxBytes
  143. }
  144. }
  145. // WithMiddlewares adds given middlewares to given routes.
  146. func WithMiddlewares(ms []Middleware, rs ...Route) []Route {
  147. for i := len(ms) - 1; i >= 0; i-- {
  148. rs = WithMiddleware(ms[i], rs...)
  149. }
  150. return rs
  151. }
  152. // WithMiddleware adds given middleware to given route.
  153. func WithMiddleware(middleware Middleware, rs ...Route) []Route {
  154. routes := make([]Route, len(rs))
  155. for i := range rs {
  156. route := rs[i]
  157. routes[i] = Route{
  158. Method: route.Method,
  159. Path: route.Path,
  160. Handler: middleware(route.Handler),
  161. }
  162. }
  163. return routes
  164. }
  165. // WithNotFoundHandler returns a RunOption with not found handler set to given handler.
  166. func WithNotFoundHandler(handler http.Handler) RunOption {
  167. return func(server *Server) {
  168. notFoundHandler := server.ngin.notFoundHandler(handler)
  169. server.router.SetNotFoundHandler(notFoundHandler)
  170. }
  171. }
  172. // WithNotAllowedHandler returns a RunOption with not allowed handler set to given handler.
  173. func WithNotAllowedHandler(handler http.Handler) RunOption {
  174. return func(server *Server) {
  175. server.router.SetNotAllowedHandler(handler)
  176. }
  177. }
  178. // WithPrefix adds group as a prefix to the route paths.
  179. func WithPrefix(group string) RouteOption {
  180. return func(r *featuredRoutes) {
  181. var routes []Route
  182. for _, rt := range r.routes {
  183. p := path.Join(group, rt.Path)
  184. routes = append(routes, Route{
  185. Method: rt.Method,
  186. Path: p,
  187. Handler: rt.Handler,
  188. })
  189. }
  190. r.routes = routes
  191. }
  192. }
  193. // WithPriority returns a RunOption with priority.
  194. func WithPriority() RouteOption {
  195. return func(r *featuredRoutes) {
  196. r.priority = true
  197. }
  198. }
  199. // WithRouter returns a RunOption that make server run with given router.
  200. func WithRouter(router httpx.Router) RunOption {
  201. return func(server *Server) {
  202. server.router = router
  203. }
  204. }
  205. // WithSignature returns a RouteOption to enable signature verification.
  206. func WithSignature(signature SignatureConf) RouteOption {
  207. return func(r *featuredRoutes) {
  208. r.signature.enabled = true
  209. r.signature.Strict = signature.Strict
  210. r.signature.Expiry = signature.Expiry
  211. r.signature.PrivateKeys = signature.PrivateKeys
  212. }
  213. }
  214. // WithTimeout returns a RouteOption to set timeout with given value.
  215. func WithTimeout(timeout time.Duration) RouteOption {
  216. return func(r *featuredRoutes) {
  217. r.timeout = timeout
  218. }
  219. }
  220. // WithTLSConfig returns a RunOption that with given tls config.
  221. func WithTLSConfig(cfg *tls.Config) RunOption {
  222. return func(svr *Server) {
  223. svr.ngin.setTlsConfig(cfg)
  224. }
  225. }
  226. // WithUnauthorizedCallback returns a RunOption that with given unauthorized callback set.
  227. func WithUnauthorizedCallback(callback handler.UnauthorizedCallback) RunOption {
  228. return func(svr *Server) {
  229. svr.ngin.setUnauthorizedCallback(callback)
  230. }
  231. }
  232. // WithUnsignedCallback returns a RunOption that with given unsigned callback set.
  233. func WithUnsignedCallback(callback handler.UnsignedCallback) RunOption {
  234. return func(svr *Server) {
  235. svr.ngin.setUnsignedCallback(callback)
  236. }
  237. }
  238. func handleError(err error) {
  239. // ErrServerClosed means the server is closed manually
  240. if err == nil || err == http.ErrServerClosed {
  241. return
  242. }
  243. logx.Error(err)
  244. panic(err)
  245. }
  246. func validateSecret(secret string) {
  247. if len(secret) < 8 {
  248. panic("secret's length can't be less than 8")
  249. }
  250. }
  251. type corsRouter struct {
  252. httpx.Router
  253. middleware Middleware
  254. }
  255. func newCorsRouter(router httpx.Router, headerFn func(http.Header), origins ...string) httpx.Router {
  256. return &corsRouter{
  257. Router: router,
  258. middleware: cors.Middleware(headerFn, origins...),
  259. }
  260. }
  261. func (c *corsRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  262. c.middleware(c.Router.ServeHTTP)(w, r)
  263. }