server.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. package rest
  2. import (
  3. "crypto/tls"
  4. "log"
  5. "net/http"
  6. "path"
  7. "time"
  8. "github.com/zeromicro/go-zero/core/logx"
  9. "github.com/zeromicro/go-zero/rest/chain"
  10. "github.com/zeromicro/go-zero/rest/handler"
  11. "github.com/zeromicro/go-zero/rest/httpx"
  12. "github.com/zeromicro/go-zero/rest/internal"
  13. "github.com/zeromicro/go-zero/rest/internal/cors"
  14. "github.com/zeromicro/go-zero/rest/router"
  15. )
  16. type (
  17. // RunOption defines the method to customize a Server.
  18. RunOption func(*Server)
  19. // StartOption defines the method to customize http server.
  20. StartOption func(svr *http.Server)
  21. // A Server is a http server.
  22. Server struct {
  23. ngin *engine
  24. router httpx.Router
  25. }
  26. )
  27. // MustNewServer returns a server with given config of c and options defined in opts.
  28. // Be aware that later RunOption might overwrite previous one that write the same option.
  29. // The process will exit if error occurs.
  30. func MustNewServer(c RestConf, opts ...RunOption) *Server {
  31. server, err := NewServer(c, opts...)
  32. if err != nil {
  33. log.Fatal(err)
  34. }
  35. return server
  36. }
  37. // NewServer returns a server with given config of c and options defined in opts.
  38. // Be aware that later RunOption might overwrite previous one that write the same option.
  39. func NewServer(c RestConf, opts ...RunOption) (*Server, error) {
  40. if err := c.SetUp(); err != nil {
  41. return nil, err
  42. }
  43. server := &Server{
  44. ngin: newEngine(c),
  45. router: router.NewRouter(),
  46. }
  47. opts = append([]RunOption{WithNotFoundHandler(nil)}, opts...)
  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. // PrintRoutes prints the added routes to stdout.
  68. func (s *Server) PrintRoutes() {
  69. s.ngin.print()
  70. }
  71. // Routes returns the HTTP routers that registered in the server.
  72. func (s *Server) Routes() []Route {
  73. var routes []Route
  74. for _, r := range s.ngin.routes {
  75. routes = append(routes, r.routes...)
  76. }
  77. return routes
  78. }
  79. // ServeHTTP is for test purpose, allow developer to do a unit test with
  80. // all defined router without starting an HTTP Server.
  81. //
  82. // For example:
  83. //
  84. // server := MustNewServer(...)
  85. // server.addRoute(...) // router a
  86. // server.addRoute(...) // router b
  87. // server.addRoute(...) // router c
  88. //
  89. // r, _ := http.NewRequest(...)
  90. // w := httptest.NewRecorder(...)
  91. // server.ServeHTTP(w, r)
  92. // // verify the response
  93. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  94. s.ngin.bindRoutes(s.router)
  95. s.router.ServeHTTP(w, r)
  96. }
  97. // Start starts the Server.
  98. // Graceful shutdown is enabled by default.
  99. // Use proc.SetTimeToForceQuit to customize the graceful shutdown period.
  100. func (s *Server) Start(opts ...StartOption) {
  101. var startOption []internal.StartOption
  102. for _, opt := range opts {
  103. startOption = append(startOption, internal.StartOption(opt))
  104. }
  105. handleError(s.ngin.start(s.router, startOption...))
  106. }
  107. // Stop stops the Server.
  108. func (s *Server) Stop() {
  109. logx.Close()
  110. }
  111. // Use adds the given middleware in the Server.
  112. func (s *Server) Use(middleware Middleware) {
  113. s.ngin.use(middleware)
  114. }
  115. // ToMiddleware converts the given handler to a Middleware.
  116. func ToMiddleware(handler func(next http.Handler) http.Handler) Middleware {
  117. return func(handle http.HandlerFunc) http.HandlerFunc {
  118. return handler(handle).ServeHTTP
  119. }
  120. }
  121. // WithChain returns a RunOption that uses the given chain to replace the default chain.
  122. // JWT auth middleware and the middlewares that added by svr.Use() will be appended.
  123. func WithChain(chn chain.Chain) RunOption {
  124. return func(svr *Server) {
  125. svr.ngin.chain = chn
  126. }
  127. }
  128. // WithCors returns a func to enable CORS for given origin, or default to all origins (*).
  129. func WithCors(origin ...string) RunOption {
  130. return func(server *Server) {
  131. server.router.SetNotAllowedHandler(cors.NotAllowedHandler(nil, origin...))
  132. server.router = newCorsRouter(server.router, nil, origin...)
  133. }
  134. }
  135. // WithCustomCors returns a func to enable CORS for given origin, or default to all origins (*),
  136. // fn lets caller customizing the response.
  137. func WithCustomCors(middlewareFn func(header http.Header), notAllowedFn func(http.ResponseWriter),
  138. origin ...string) RunOption {
  139. return func(server *Server) {
  140. server.router.SetNotAllowedHandler(cors.NotAllowedHandler(notAllowedFn, origin...))
  141. server.router = newCorsRouter(server.router, middlewareFn, origin...)
  142. }
  143. }
  144. // WithJwt returns a func to enable jwt authentication in given route.
  145. func WithJwt(secret string) RouteOption {
  146. return func(r *featuredRoutes) {
  147. validateSecret(secret)
  148. r.jwt.enabled = true
  149. r.jwt.secret = secret
  150. }
  151. }
  152. // WithJwtTransition returns a func to enable jwt authentication as well as jwt secret transition.
  153. // Which means old and new jwt secrets work together for a period.
  154. func WithJwtTransition(secret, prevSecret string) RouteOption {
  155. return func(r *featuredRoutes) {
  156. // why not validate prevSecret, because prevSecret is an already used one,
  157. // even it not meet our requirement, we still need to allow the transition.
  158. validateSecret(secret)
  159. r.jwt.enabled = true
  160. r.jwt.secret = secret
  161. r.jwt.prevSecret = prevSecret
  162. }
  163. }
  164. // WithMaxBytes returns a RouteOption to set maxBytes with the given value.
  165. func WithMaxBytes(maxBytes int64) RouteOption {
  166. return func(r *featuredRoutes) {
  167. r.maxBytes = maxBytes
  168. }
  169. }
  170. // WithMiddlewares adds given middlewares to given routes.
  171. func WithMiddlewares(ms []Middleware, rs ...Route) []Route {
  172. for i := len(ms) - 1; i >= 0; i-- {
  173. rs = WithMiddleware(ms[i], rs...)
  174. }
  175. return rs
  176. }
  177. // WithMiddleware adds given middleware to given route.
  178. func WithMiddleware(middleware Middleware, rs ...Route) []Route {
  179. routes := make([]Route, len(rs))
  180. for i := range rs {
  181. route := rs[i]
  182. routes[i] = Route{
  183. Method: route.Method,
  184. Path: route.Path,
  185. Handler: middleware(route.Handler),
  186. }
  187. }
  188. return routes
  189. }
  190. // WithNotFoundHandler returns a RunOption with not found handler set to given handler.
  191. func WithNotFoundHandler(handler http.Handler) RunOption {
  192. return func(server *Server) {
  193. notFoundHandler := server.ngin.notFoundHandler(handler)
  194. server.router.SetNotFoundHandler(notFoundHandler)
  195. }
  196. }
  197. // WithNotAllowedHandler returns a RunOption with not allowed handler set to given handler.
  198. func WithNotAllowedHandler(handler http.Handler) RunOption {
  199. return func(server *Server) {
  200. server.router.SetNotAllowedHandler(handler)
  201. }
  202. }
  203. // WithPrefix adds group as a prefix to the route paths.
  204. func WithPrefix(group string) RouteOption {
  205. return func(r *featuredRoutes) {
  206. var routes []Route
  207. for _, rt := range r.routes {
  208. p := path.Join(group, rt.Path)
  209. routes = append(routes, Route{
  210. Method: rt.Method,
  211. Path: p,
  212. Handler: rt.Handler,
  213. })
  214. }
  215. r.routes = routes
  216. }
  217. }
  218. // WithPriority returns a RunOption with priority.
  219. func WithPriority() RouteOption {
  220. return func(r *featuredRoutes) {
  221. r.priority = true
  222. }
  223. }
  224. // WithRouter returns a RunOption that make server run with given router.
  225. func WithRouter(router httpx.Router) RunOption {
  226. return func(server *Server) {
  227. server.router = router
  228. }
  229. }
  230. // WithSignature returns a RouteOption to enable signature verification.
  231. func WithSignature(signature SignatureConf) RouteOption {
  232. return func(r *featuredRoutes) {
  233. r.signature.enabled = true
  234. r.signature.Strict = signature.Strict
  235. r.signature.Expiry = signature.Expiry
  236. r.signature.PrivateKeys = signature.PrivateKeys
  237. }
  238. }
  239. // WithTimeout returns a RouteOption to set timeout with given value.
  240. func WithTimeout(timeout time.Duration) RouteOption {
  241. return func(r *featuredRoutes) {
  242. r.timeout = timeout
  243. }
  244. }
  245. // WithTLSConfig returns a RunOption that with given tls config.
  246. func WithTLSConfig(cfg *tls.Config) RunOption {
  247. return func(svr *Server) {
  248. svr.ngin.setTlsConfig(cfg)
  249. }
  250. }
  251. // WithUnauthorizedCallback returns a RunOption that with given unauthorized callback set.
  252. func WithUnauthorizedCallback(callback handler.UnauthorizedCallback) RunOption {
  253. return func(svr *Server) {
  254. svr.ngin.setUnauthorizedCallback(callback)
  255. }
  256. }
  257. // WithUnsignedCallback returns a RunOption that with given unsigned callback set.
  258. func WithUnsignedCallback(callback handler.UnsignedCallback) RunOption {
  259. return func(svr *Server) {
  260. svr.ngin.setUnsignedCallback(callback)
  261. }
  262. }
  263. func handleError(err error) {
  264. // ErrServerClosed means the server is closed manually
  265. if err == nil || err == http.ErrServerClosed {
  266. return
  267. }
  268. logx.Error(err)
  269. panic(err)
  270. }
  271. func validateSecret(secret string) {
  272. if len(secret) < 8 {
  273. panic("secret's length can't be less than 8")
  274. }
  275. }
  276. type corsRouter struct {
  277. httpx.Router
  278. middleware Middleware
  279. }
  280. func newCorsRouter(router httpx.Router, headerFn func(http.Header), origins ...string) httpx.Router {
  281. return &corsRouter{
  282. Router: router,
  283. middleware: cors.Middleware(headerFn, origins...),
  284. }
  285. }
  286. func (c *corsRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  287. c.middleware(c.Router.ServeHTTP)(w, r)
  288. }