server.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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 func(*Server)
  15. Server struct {
  16. ngin *engine
  17. opts runOptions
  18. }
  19. )
  20. // MustNewServer returns a server with given config of c and options defined in opts.
  21. // Be aware that later RunOption might overwrite previous one that write the same option.
  22. // The process will exit if error occurs.
  23. func MustNewServer(c RestConf, opts ...RunOption) *Server {
  24. engine, err := NewServer(c, opts...)
  25. if err != nil {
  26. log.Fatal(err)
  27. }
  28. return engine
  29. }
  30. // NewServer returns a server with given config of c and options defined in opts.
  31. // Be aware that later RunOption might overwrite previous one that write the same option.
  32. func NewServer(c RestConf, opts ...RunOption) (*Server, error) {
  33. if err := c.SetUp(); err != nil {
  34. return nil, err
  35. }
  36. server := &Server{
  37. ngin: newEngine(c),
  38. opts: runOptions{
  39. start: func(srv *engine) error {
  40. return srv.Start()
  41. },
  42. },
  43. }
  44. for _, opt := range opts {
  45. opt(server)
  46. }
  47. return server, nil
  48. }
  49. func (e *Server) AddRoutes(rs []Route, opts ...RouteOption) {
  50. r := featuredRoutes{
  51. routes: rs,
  52. }
  53. for _, opt := range opts {
  54. opt(&r)
  55. }
  56. e.ngin.AddRoutes(r)
  57. }
  58. func (e *Server) AddRoute(r Route, opts ...RouteOption) {
  59. e.AddRoutes([]Route{r}, opts...)
  60. }
  61. func (e *Server) Start() {
  62. handleError(e.opts.start(e.ngin))
  63. }
  64. func (e *Server) Stop() {
  65. logx.Close()
  66. }
  67. func (e *Server) Use(middleware Middleware) {
  68. e.ngin.use(middleware)
  69. }
  70. func ToMiddleware(handler func(next http.Handler) http.Handler) Middleware {
  71. return func(handle http.HandlerFunc) http.HandlerFunc {
  72. return handler(handle).ServeHTTP
  73. }
  74. }
  75. func WithJwt(secret string) RouteOption {
  76. return func(r *featuredRoutes) {
  77. validateSecret(secret)
  78. r.jwt.enabled = true
  79. r.jwt.secret = secret
  80. }
  81. }
  82. func WithJwtTransition(secret, prevSecret string) RouteOption {
  83. return func(r *featuredRoutes) {
  84. // why not validate prevSecret, because prevSecret is an already used one,
  85. // even it not meet our requirement, we still need to allow the transition.
  86. validateSecret(secret)
  87. r.jwt.enabled = true
  88. r.jwt.secret = secret
  89. r.jwt.prevSecret = prevSecret
  90. }
  91. }
  92. func WithMiddlewares(ms []Middleware, rs ...Route) []Route {
  93. for i := len(ms) - 1; i >= 0; i-- {
  94. rs = WithMiddleware(ms[i], rs...)
  95. }
  96. return rs
  97. }
  98. func WithMiddleware(middleware Middleware, rs ...Route) []Route {
  99. routes := make([]Route, len(rs))
  100. for i := range rs {
  101. route := rs[i]
  102. routes[i] = Route{
  103. Method: route.Method,
  104. Path: route.Path,
  105. Handler: middleware(route.Handler),
  106. }
  107. }
  108. return routes
  109. }
  110. func WithNotFoundHandler(handler http.Handler) RunOption {
  111. rt := router.NewRouter()
  112. rt.SetNotFoundHandler(handler)
  113. return WithRouter(rt)
  114. }
  115. func WithNotAllowedHandler(handler http.Handler) RunOption {
  116. rt := router.NewRouter()
  117. rt.SetNotAllowedHandler(handler)
  118. return WithRouter(rt)
  119. }
  120. func WithPriority() RouteOption {
  121. return func(r *featuredRoutes) {
  122. r.priority = true
  123. }
  124. }
  125. func WithRouter(router httpx.Router) RunOption {
  126. return func(server *Server) {
  127. server.opts.start = func(srv *engine) error {
  128. return srv.StartWithRouter(router)
  129. }
  130. }
  131. }
  132. func WithSignature(signature SignatureConf) RouteOption {
  133. return func(r *featuredRoutes) {
  134. r.signature.enabled = true
  135. r.signature.Strict = signature.Strict
  136. r.signature.Expiry = signature.Expiry
  137. r.signature.PrivateKeys = signature.PrivateKeys
  138. }
  139. }
  140. func WithUnauthorizedCallback(callback handler.UnauthorizedCallback) RunOption {
  141. return func(engine *Server) {
  142. engine.ngin.SetUnauthorizedCallback(callback)
  143. }
  144. }
  145. func WithUnsignedCallback(callback handler.UnsignedCallback) RunOption {
  146. return func(engine *Server) {
  147. engine.ngin.SetUnsignedCallback(callback)
  148. }
  149. }
  150. func handleError(err error) {
  151. // ErrServerClosed means the server is closed manually
  152. if err == nil || err == http.ErrServerClosed {
  153. return
  154. }
  155. logx.Error(err)
  156. panic(err)
  157. }
  158. func validateSecret(secret string) {
  159. if len(secret) < 8 {
  160. panic("secret's length can't be less than 8")
  161. }
  162. }