server.go 6.0 KB

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