server.go 3.3 KB

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