server.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. package rest
  2. import (
  3. "crypto/tls"
  4. "log"
  5. "net/http"
  6. "path"
  7. "time"
  8. "github.com/tal-tech/go-zero/core/logx"
  9. "github.com/tal-tech/go-zero/rest/handler"
  10. "github.com/tal-tech/go-zero/rest/httpx"
  11. "github.com/tal-tech/go-zero/rest/internal/cors"
  12. "github.com/tal-tech/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. for _, opt := range opts {
  44. opt(server)
  45. }
  46. return server, nil
  47. }
  48. // AddRoutes add given routes into the Server.
  49. func (s *Server) AddRoutes(rs []Route, opts ...RouteOption) {
  50. r := featuredRoutes{
  51. routes: rs,
  52. }
  53. for _, opt := range opts {
  54. opt(&r)
  55. }
  56. s.ngin.addRoutes(r)
  57. }
  58. // AddRoute adds given route into the Server.
  59. func (s *Server) AddRoute(r Route, opts ...RouteOption) {
  60. s.AddRoutes([]Route{r}, opts...)
  61. }
  62. // Start starts the Server.
  63. // Graceful shutdown is enabled by default.
  64. // Use proc.SetTimeToForceQuit to customize the graceful shutdown period.
  65. func (s *Server) Start() {
  66. handleError(s.ngin.start(s.router))
  67. }
  68. // Stop stops the Server.
  69. func (s *Server) Stop() {
  70. logx.Close()
  71. }
  72. // Use adds the given middleware in the Server.
  73. func (s *Server) Use(middleware Middleware) {
  74. s.ngin.use(middleware)
  75. }
  76. // ToMiddleware converts the given handler to a Middleware.
  77. func ToMiddleware(handler func(next http.Handler) http.Handler) Middleware {
  78. return func(handle http.HandlerFunc) http.HandlerFunc {
  79. return handler(handle).ServeHTTP
  80. }
  81. }
  82. // WithCors returns a func to enable CORS for given origin, or default to all origins (*).
  83. func WithCors(origin ...string) RunOption {
  84. return func(server *Server) {
  85. server.router.SetNotAllowedHandler(cors.NotAllowedHandler(origin...))
  86. server.Use(cors.Middleware(origin...))
  87. }
  88. }
  89. // WithJwt returns a func to enable jwt authentication in given route.
  90. func WithJwt(secret string) RouteOption {
  91. return func(r *featuredRoutes) {
  92. validateSecret(secret)
  93. r.jwt.enabled = true
  94. r.jwt.secret = secret
  95. }
  96. }
  97. // WithJwtTransition returns a func to enable jwt authentication as well as jwt secret transition.
  98. // Which means old and new jwt secrets work together for a period.
  99. func WithJwtTransition(secret, prevSecret string) RouteOption {
  100. return func(r *featuredRoutes) {
  101. // why not validate prevSecret, because prevSecret is an already used one,
  102. // even it not meet our requirement, we still need to allow the transition.
  103. validateSecret(secret)
  104. r.jwt.enabled = true
  105. r.jwt.secret = secret
  106. r.jwt.prevSecret = prevSecret
  107. }
  108. }
  109. // WithMiddlewares adds given middlewares to given routes.
  110. func WithMiddlewares(ms []Middleware, rs ...Route) []Route {
  111. for i := len(ms) - 1; i >= 0; i-- {
  112. rs = WithMiddleware(ms[i], rs...)
  113. }
  114. return rs
  115. }
  116. // WithMiddleware adds given middleware to given route.
  117. func WithMiddleware(middleware Middleware, rs ...Route) []Route {
  118. routes := make([]Route, len(rs))
  119. for i := range rs {
  120. route := rs[i]
  121. routes[i] = Route{
  122. Method: route.Method,
  123. Path: route.Path,
  124. Handler: middleware(route.Handler),
  125. }
  126. }
  127. return routes
  128. }
  129. // WithNotFoundHandler returns a RunOption with not found handler set to given handler.
  130. func WithNotFoundHandler(handler http.Handler) RunOption {
  131. return func(server *Server) {
  132. server.router.SetNotFoundHandler(handler)
  133. }
  134. }
  135. // WithNotAllowedHandler returns a RunOption with not allowed handler set to given handler.
  136. func WithNotAllowedHandler(handler http.Handler) RunOption {
  137. return func(server *Server) {
  138. server.router.SetNotAllowedHandler(handler)
  139. }
  140. }
  141. // WithPrefix adds group as a prefix to the route paths.
  142. func WithPrefix(group string) RouteOption {
  143. return func(r *featuredRoutes) {
  144. var routes []Route
  145. for _, rt := range r.routes {
  146. p := path.Join(group, rt.Path)
  147. routes = append(routes, Route{
  148. Method: rt.Method,
  149. Path: p,
  150. Handler: rt.Handler,
  151. })
  152. }
  153. r.routes = routes
  154. }
  155. }
  156. // WithPriority returns a RunOption with priority.
  157. func WithPriority() RouteOption {
  158. return func(r *featuredRoutes) {
  159. r.priority = true
  160. }
  161. }
  162. // WithRouter returns a RunOption that make server run with given router.
  163. func WithRouter(router httpx.Router) RunOption {
  164. return func(server *Server) {
  165. server.router = router
  166. }
  167. }
  168. // WithSignature returns a RouteOption to enable signature verification.
  169. func WithSignature(signature SignatureConf) RouteOption {
  170. return func(r *featuredRoutes) {
  171. r.signature.enabled = true
  172. r.signature.Strict = signature.Strict
  173. r.signature.Expiry = signature.Expiry
  174. r.signature.PrivateKeys = signature.PrivateKeys
  175. }
  176. }
  177. // WithTimeout returns a RouteOption to set timeout with given value.
  178. func WithTimeout(timeout time.Duration) RouteOption {
  179. return func(r *featuredRoutes) {
  180. r.timeout = timeout
  181. }
  182. }
  183. // WithTLSConfig returns a RunOption that with given tls config.
  184. func WithTLSConfig(cfg *tls.Config) RunOption {
  185. return func(srv *Server) {
  186. srv.ngin.setTlsConfig(cfg)
  187. }
  188. }
  189. // WithUnauthorizedCallback returns a RunOption that with given unauthorized callback set.
  190. func WithUnauthorizedCallback(callback handler.UnauthorizedCallback) RunOption {
  191. return func(srv *Server) {
  192. srv.ngin.setUnauthorizedCallback(callback)
  193. }
  194. }
  195. // WithUnsignedCallback returns a RunOption that with given unsigned callback set.
  196. func WithUnsignedCallback(callback handler.UnsignedCallback) RunOption {
  197. return func(srv *Server) {
  198. srv.ngin.setUnsignedCallback(callback)
  199. }
  200. }
  201. func handleError(err error) {
  202. // ErrServerClosed means the server is closed manually
  203. if err == nil || err == http.ErrServerClosed {
  204. return
  205. }
  206. logx.Error(err)
  207. panic(err)
  208. }
  209. func validateSecret(secret string) {
  210. if len(secret) < 8 {
  211. panic("secret's length can't be less than 8")
  212. }
  213. }