server.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. func (e *Server) Start() {
  67. handleError(e.opts.start(e.ngin))
  68. }
  69. // Stop stops the Server.
  70. func (e *Server) Stop() {
  71. logx.Close()
  72. }
  73. // Use adds the given middleware in the Server.
  74. func (e *Server) Use(middleware Middleware) {
  75. e.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. // WithJwt returns a func to enable jwt authentication in given route.
  84. func WithJwt(secret string) RouteOption {
  85. return func(r *featuredRoutes) {
  86. validateSecret(secret)
  87. r.jwt.enabled = true
  88. r.jwt.secret = secret
  89. }
  90. }
  91. // WithJwtTransition returns a func to enable jwt authentication as well as jwt secret transition.
  92. // Which means old and new jwt secrets work together for a peroid.
  93. func WithJwtTransition(secret, prevSecret string) RouteOption {
  94. return func(r *featuredRoutes) {
  95. // why not validate prevSecret, because prevSecret is an already used one,
  96. // even it not meet our requirement, we still need to allow the transition.
  97. validateSecret(secret)
  98. r.jwt.enabled = true
  99. r.jwt.secret = secret
  100. r.jwt.prevSecret = prevSecret
  101. }
  102. }
  103. // WithMiddlewares adds given middlewares to given routes.
  104. func WithMiddlewares(ms []Middleware, rs ...Route) []Route {
  105. for i := len(ms) - 1; i >= 0; i-- {
  106. rs = WithMiddleware(ms[i], rs...)
  107. }
  108. return rs
  109. }
  110. // WithMiddleware adds given middleware to given route.
  111. func WithMiddleware(middleware Middleware, rs ...Route) []Route {
  112. routes := make([]Route, len(rs))
  113. for i := range rs {
  114. route := rs[i]
  115. routes[i] = Route{
  116. Method: route.Method,
  117. Path: route.Path,
  118. Handler: middleware(route.Handler),
  119. }
  120. }
  121. return routes
  122. }
  123. // WithNotFoundHandler returns a RunOption with not found handler set to given handler.
  124. func WithNotFoundHandler(handler http.Handler) RunOption {
  125. rt := router.NewRouter()
  126. rt.SetNotFoundHandler(handler)
  127. return WithRouter(rt)
  128. }
  129. // WithNotAllowedHandler returns a RunOption with not allowed handler set to given handler.
  130. func WithNotAllowedHandler(handler http.Handler) RunOption {
  131. rt := router.NewRouter()
  132. rt.SetNotAllowedHandler(handler)
  133. return WithRouter(rt)
  134. }
  135. // WithPriority returns a RunOption with priority.
  136. func WithPriority() RouteOption {
  137. return func(r *featuredRoutes) {
  138. r.priority = true
  139. }
  140. }
  141. // WithRouter returns a RunOption that make server run with given router.
  142. func WithRouter(router httpx.Router) RunOption {
  143. return func(server *Server) {
  144. server.opts.start = func(srv *engine) error {
  145. return srv.StartWithRouter(router)
  146. }
  147. }
  148. }
  149. // WithSignature returns a RouteOption to enable signature verification.
  150. func WithSignature(signature SignatureConf) RouteOption {
  151. return func(r *featuredRoutes) {
  152. r.signature.enabled = true
  153. r.signature.Strict = signature.Strict
  154. r.signature.Expiry = signature.Expiry
  155. r.signature.PrivateKeys = signature.PrivateKeys
  156. }
  157. }
  158. // WithUnauthorizedCallback returns a RunOption that with given unauthorized callback set.
  159. func WithUnauthorizedCallback(callback handler.UnauthorizedCallback) RunOption {
  160. return func(engine *Server) {
  161. engine.ngin.SetUnauthorizedCallback(callback)
  162. }
  163. }
  164. // WithUnsignedCallback returns a RunOption that with given unsigned callback set.
  165. func WithUnsignedCallback(callback handler.UnsignedCallback) RunOption {
  166. return func(engine *Server) {
  167. engine.ngin.SetUnsignedCallback(callback)
  168. }
  169. }
  170. func handleError(err error) {
  171. // ErrServerClosed means the server is closed manually
  172. if err == nil || err == http.ErrServerClosed {
  173. return
  174. }
  175. logx.Error(err)
  176. panic(err)
  177. }
  178. func validateSecret(secret string) {
  179. if len(secret) < 8 {
  180. panic("secret's length can't be less than 8")
  181. }
  182. }