server.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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/handler"
  10. "github.com/zeromicro/go-zero/rest/httpx"
  11. "github.com/zeromicro/go-zero/rest/internal/cors"
  12. "github.com/zeromicro/go-zero/rest/router"
  13. )
  14. type (
  15. // RunOption defines the method to customize a Server.
  16. RunOption func(*Server)
  17. // A Server is a http server.
  18. Server struct {
  19. ngin *engine
  20. router httpx.Router
  21. }
  22. )
  23. // MustNewServer returns a server with given config of c and options defined in opts.
  24. // Be aware that later RunOption might overwrite previous one that write the same option.
  25. // The process will exit if error occurs.
  26. func MustNewServer(c RestConf, opts ...RunOption) *Server {
  27. server, err := NewServer(c, opts...)
  28. if err != nil {
  29. log.Fatal(err)
  30. }
  31. return server
  32. }
  33. // NewServer returns a server with given config of c and options defined in opts.
  34. // Be aware that later RunOption might overwrite previous one that write the same option.
  35. func NewServer(c RestConf, opts ...RunOption) (*Server, error) {
  36. if err := c.SetUp(); err != nil {
  37. return nil, err
  38. }
  39. server := &Server{
  40. ngin: newEngine(c),
  41. router: router.NewRouter(),
  42. }
  43. opts = append([]RunOption{WithNotFoundHandler(nil)}, opts...)
  44. for _, opt := range opts {
  45. opt(server)
  46. }
  47. return server, nil
  48. }
  49. // AddRoutes add given routes into the Server.
  50. func (s *Server) AddRoutes(rs []Route, opts ...RouteOption) {
  51. r := featuredRoutes{
  52. routes: rs,
  53. }
  54. for _, opt := range opts {
  55. opt(&r)
  56. }
  57. s.ngin.addRoutes(r)
  58. }
  59. // AddRoute adds given route into the Server.
  60. func (s *Server) AddRoute(r Route, opts ...RouteOption) {
  61. s.AddRoutes([]Route{r}, opts...)
  62. }
  63. // Start starts the Server.
  64. // Graceful shutdown is enabled by default.
  65. // Use proc.SetTimeToForceQuit to customize the graceful shutdown period.
  66. func (s *Server) Start() {
  67. handleError(s.ngin.start(s.router))
  68. }
  69. // Stop stops the Server.
  70. func (s *Server) Stop() {
  71. logx.Close()
  72. }
  73. // Use adds the given middleware in the Server.
  74. func (s *Server) Use(middleware Middleware) {
  75. s.ngin.use(middleware)
  76. }
  77. // ToMiddleware converts the given handler to a Middleware.
  78. func ToMiddleware(handler func(next http.Handler) http.Handler) Middleware {
  79. return func(handle http.HandlerFunc) http.HandlerFunc {
  80. return handler(handle).ServeHTTP
  81. }
  82. }
  83. // WithCors returns a func to enable CORS for given origin, or default to all origins (*).
  84. func WithCors(origin ...string) RunOption {
  85. return func(server *Server) {
  86. server.router.SetNotAllowedHandler(cors.NotAllowedHandler(nil, origin...))
  87. server.Use(cors.Middleware(nil, origin...))
  88. }
  89. }
  90. // WithCustomCors returns a func to enable CORS for given origin, or default to all origins (*),
  91. // fn lets caller customizing the response.
  92. func WithCustomCors(middlewareFn func(header http.Header), notAllowedFn func(http.ResponseWriter),
  93. origin ...string) RunOption {
  94. return func(server *Server) {
  95. server.router.SetNotAllowedHandler(cors.NotAllowedHandler(notAllowedFn, origin...))
  96. server.Use(cors.Middleware(middlewareFn, origin...))
  97. }
  98. }
  99. // WithJwt returns a func to enable jwt authentication in given route.
  100. func WithJwt(secret string) RouteOption {
  101. return func(r *featuredRoutes) {
  102. validateSecret(secret)
  103. r.jwt.enabled = true
  104. r.jwt.secret = secret
  105. }
  106. }
  107. // WithJwtTransition returns a func to enable jwt authentication as well as jwt secret transition.
  108. // Which means old and new jwt secrets work together for a period.
  109. func WithJwtTransition(secret, prevSecret string) RouteOption {
  110. return func(r *featuredRoutes) {
  111. // why not validate prevSecret, because prevSecret is an already used one,
  112. // even it not meet our requirement, we still need to allow the transition.
  113. validateSecret(secret)
  114. r.jwt.enabled = true
  115. r.jwt.secret = secret
  116. r.jwt.prevSecret = prevSecret
  117. }
  118. }
  119. // WithMaxBytes returns a RouteOption to set maxBytes with the given value.
  120. func WithMaxBytes(maxBytes int64) RouteOption {
  121. return func(r *featuredRoutes) {
  122. r.maxBytes = maxBytes
  123. }
  124. }
  125. // WithMiddlewares adds given middlewares to given routes.
  126. func WithMiddlewares(ms []Middleware, rs ...Route) []Route {
  127. for i := len(ms) - 1; i >= 0; i-- {
  128. rs = WithMiddleware(ms[i], rs...)
  129. }
  130. return rs
  131. }
  132. // WithMiddleware adds given middleware to given route.
  133. func WithMiddleware(middleware Middleware, rs ...Route) []Route {
  134. routes := make([]Route, len(rs))
  135. for i := range rs {
  136. route := rs[i]
  137. routes[i] = Route{
  138. Method: route.Method,
  139. Path: route.Path,
  140. Handler: middleware(route.Handler),
  141. }
  142. }
  143. return routes
  144. }
  145. // WithNotFoundHandler returns a RunOption with not found handler set to given handler.
  146. func WithNotFoundHandler(handler http.Handler) RunOption {
  147. return func(server *Server) {
  148. notFoundHandler := server.ngin.notFoundHandler(handler)
  149. server.router.SetNotFoundHandler(notFoundHandler)
  150. }
  151. }
  152. // WithNotAllowedHandler returns a RunOption with not allowed handler set to given handler.
  153. func WithNotAllowedHandler(handler http.Handler) RunOption {
  154. return func(server *Server) {
  155. server.router.SetNotAllowedHandler(handler)
  156. }
  157. }
  158. // WithPrefix adds group as a prefix to the route paths.
  159. func WithPrefix(group string) RouteOption {
  160. return func(r *featuredRoutes) {
  161. var routes []Route
  162. for _, rt := range r.routes {
  163. p := path.Join(group, rt.Path)
  164. routes = append(routes, Route{
  165. Method: rt.Method,
  166. Path: p,
  167. Handler: rt.Handler,
  168. })
  169. }
  170. r.routes = routes
  171. }
  172. }
  173. // WithPriority returns a RunOption with priority.
  174. func WithPriority() RouteOption {
  175. return func(r *featuredRoutes) {
  176. r.priority = true
  177. }
  178. }
  179. // WithRouter returns a RunOption that make server run with given router.
  180. func WithRouter(router httpx.Router) RunOption {
  181. return func(server *Server) {
  182. server.router = router
  183. }
  184. }
  185. // WithSignature returns a RouteOption to enable signature verification.
  186. func WithSignature(signature SignatureConf) RouteOption {
  187. return func(r *featuredRoutes) {
  188. r.signature.enabled = true
  189. r.signature.Strict = signature.Strict
  190. r.signature.Expiry = signature.Expiry
  191. r.signature.PrivateKeys = signature.PrivateKeys
  192. }
  193. }
  194. // WithTimeout returns a RouteOption to set timeout with given value.
  195. func WithTimeout(timeout time.Duration) RouteOption {
  196. return func(r *featuredRoutes) {
  197. r.timeout = timeout
  198. }
  199. }
  200. // WithTLSConfig returns a RunOption that with given tls config.
  201. func WithTLSConfig(cfg *tls.Config) RunOption {
  202. return func(svr *Server) {
  203. svr.ngin.setTlsConfig(cfg)
  204. }
  205. }
  206. // WithUnauthorizedCallback returns a RunOption that with given unauthorized callback set.
  207. func WithUnauthorizedCallback(callback handler.UnauthorizedCallback) RunOption {
  208. return func(svr *Server) {
  209. svr.ngin.setUnauthorizedCallback(callback)
  210. }
  211. }
  212. // WithUnsignedCallback returns a RunOption that with given unsigned callback set.
  213. func WithUnsignedCallback(callback handler.UnsignedCallback) RunOption {
  214. return func(svr *Server) {
  215. svr.ngin.setUnsignedCallback(callback)
  216. }
  217. }
  218. func handleError(err error) {
  219. // ErrServerClosed means the server is closed manually
  220. if err == nil || err == http.ErrServerClosed {
  221. return
  222. }
  223. logx.Error(err)
  224. panic(err)
  225. }
  226. func validateSecret(secret string) {
  227. if len(secret) < 8 {
  228. panic("secret's length can't be less than 8")
  229. }
  230. }