server.go 7.5 KB

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