server.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. package rest
  2. import (
  3. "log"
  4. "net/http"
  5. "github.com/tal-tech/go-zero/core/logx"
  6. "github.com/tal-tech/go-zero/rest/handler"
  7. "github.com/tal-tech/go-zero/rest/httpx"
  8. "github.com/tal-tech/go-zero/rest/router"
  9. )
  10. type (
  11. runOptions struct {
  12. start func(*engine) error
  13. }
  14. // RunOption defines the method to customize a Server.
  15. RunOption func(*Server)
  16. // A Server is a http server.
  17. Server struct {
  18. ngin *engine
  19. opts runOptions
  20. }
  21. )
  22. // MustNewServer returns a server with given config of c and options defined in opts.
  23. // Be aware that later RunOption might overwrite previous one that write the same option.
  24. // The process will exit if error occurs.
  25. func MustNewServer(c RestConf, opts ...RunOption) *Server {
  26. engine, err := NewServer(c, opts...)
  27. if err != nil {
  28. log.Fatal(err)
  29. }
  30. return engine
  31. }
  32. // NewServer returns a server with given config of c and options defined in opts.
  33. // Be aware that later RunOption might overwrite previous one that write the same option.
  34. func NewServer(c RestConf, opts ...RunOption) (*Server, error) {
  35. if err := c.SetUp(); err != nil {
  36. return nil, err
  37. }
  38. server := &Server{
  39. ngin: newEngine(c),
  40. opts: runOptions{
  41. start: func(srv *engine) error {
  42. return srv.Start()
  43. },
  44. },
  45. }
  46. for _, opt := range opts {
  47. opt(server)
  48. }
  49. return server, nil
  50. }
  51. // AddRoutes add given routes into the Server.
  52. func (e *Server) AddRoutes(rs []Route, opts ...RouteOption) {
  53. r := featuredRoutes{
  54. routes: rs,
  55. }
  56. for _, opt := range opts {
  57. opt(&r)
  58. }
  59. e.ngin.AddRoutes(r)
  60. }
  61. // AddRoute adds given route into the Server.
  62. func (e *Server) AddRoute(r Route, opts ...RouteOption) {
  63. e.AddRoutes([]Route{r}, opts...)
  64. }
  65. // Start starts the Server.
  66. // Graceful shutdown is enabled by default.
  67. // Use proc.SetTimeToForceQuit to customize the graceful shutdown period.
  68. func (e *Server) Start() {
  69. handleError(e.opts.start(e.ngin))
  70. }
  71. // Stop stops the Server.
  72. func (e *Server) Stop() {
  73. logx.Close()
  74. }
  75. // Use adds the given middleware in the Server.
  76. func (e *Server) Use(middleware Middleware) {
  77. e.ngin.use(middleware)
  78. }
  79. // ToMiddleware converts the given handler to a Middleware.
  80. func ToMiddleware(handler func(next http.Handler) http.Handler) Middleware {
  81. return func(handle http.HandlerFunc) http.HandlerFunc {
  82. return handler(handle).ServeHTTP
  83. }
  84. }
  85. // WithJwt returns a func to enable jwt authentication in given route.
  86. func WithJwt(secret string) RouteOption {
  87. return func(r *featuredRoutes) {
  88. validateSecret(secret)
  89. r.jwt.enabled = true
  90. r.jwt.secret = secret
  91. }
  92. }
  93. // WithJwtTransition returns a func to enable jwt authentication as well as jwt secret transition.
  94. // Which means old and new jwt secrets work together for a period.
  95. func WithJwtTransition(secret, prevSecret string) RouteOption {
  96. return func(r *featuredRoutes) {
  97. // why not validate prevSecret, because prevSecret is an already used one,
  98. // even it not meet our requirement, we still need to allow the transition.
  99. validateSecret(secret)
  100. r.jwt.enabled = true
  101. r.jwt.secret = secret
  102. r.jwt.prevSecret = prevSecret
  103. }
  104. }
  105. // WithMiddlewares adds given middlewares to given routes.
  106. func WithMiddlewares(ms []Middleware, rs ...Route) []Route {
  107. for i := len(ms) - 1; i >= 0; i-- {
  108. rs = WithMiddleware(ms[i], rs...)
  109. }
  110. return rs
  111. }
  112. // WithMiddleware adds given middleware to given route.
  113. func WithMiddleware(middleware Middleware, rs ...Route) []Route {
  114. routes := make([]Route, len(rs))
  115. for i := range rs {
  116. route := rs[i]
  117. routes[i] = Route{
  118. Method: route.Method,
  119. Path: route.Path,
  120. Handler: middleware(route.Handler),
  121. }
  122. }
  123. return routes
  124. }
  125. // WithNotFoundHandler returns a RunOption with not found handler set to given handler.
  126. func WithNotFoundHandler(handler http.Handler) RunOption {
  127. rt := router.NewRouter()
  128. rt.SetNotFoundHandler(handler)
  129. return WithRouter(rt)
  130. }
  131. // WithNotAllowedHandler returns a RunOption with not allowed handler set to given handler.
  132. func WithNotAllowedHandler(handler http.Handler) RunOption {
  133. rt := router.NewRouter()
  134. rt.SetNotAllowedHandler(handler)
  135. return WithRouter(rt)
  136. }
  137. // WithPriority returns a RunOption with priority.
  138. func WithPriority() RouteOption {
  139. return func(r *featuredRoutes) {
  140. r.priority = true
  141. }
  142. }
  143. // WithRouter returns a RunOption that make server run with given router.
  144. func WithRouter(router httpx.Router) RunOption {
  145. return func(server *Server) {
  146. server.opts.start = func(srv *engine) error {
  147. return srv.StartWithRouter(router)
  148. }
  149. }
  150. }
  151. // WithSignature returns a RouteOption to enable signature verification.
  152. func WithSignature(signature SignatureConf) RouteOption {
  153. return func(r *featuredRoutes) {
  154. r.signature.enabled = true
  155. r.signature.Strict = signature.Strict
  156. r.signature.Expiry = signature.Expiry
  157. r.signature.PrivateKeys = signature.PrivateKeys
  158. }
  159. }
  160. // WithUnauthorizedCallback returns a RunOption that with given unauthorized callback set.
  161. func WithUnauthorizedCallback(callback handler.UnauthorizedCallback) RunOption {
  162. return func(engine *Server) {
  163. engine.ngin.SetUnauthorizedCallback(callback)
  164. }
  165. }
  166. // WithUnsignedCallback returns a RunOption that with given unsigned callback set.
  167. func WithUnsignedCallback(callback handler.UnsignedCallback) RunOption {
  168. return func(engine *Server) {
  169. engine.ngin.SetUnsignedCallback(callback)
  170. }
  171. }
  172. func handleError(err error) {
  173. // ErrServerClosed means the server is closed manually
  174. if err == nil || err == http.ErrServerClosed {
  175. return
  176. }
  177. logx.Error(err)
  178. panic(err)
  179. }
  180. func validateSecret(secret string) {
  181. if len(secret) < 8 {
  182. panic("secret's length can't be less than 8")
  183. }
  184. }