server.go 6.8 KB

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