server.go 5.7 KB

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