2020-07-31 11:14:48 +08:00
|
|
|
package rest
|
2020-07-26 17:09:05 +08:00
|
|
|
|
|
|
|
import (
|
2021-10-31 12:56:25 +08:00
|
|
|
"crypto/tls"
|
2023-10-21 00:00:57 +08:00
|
|
|
"errors"
|
2020-07-26 17:09:05 +08:00
|
|
|
"net/http"
|
2021-11-01 20:15:10 +08:00
|
|
|
"path"
|
2021-11-03 22:20:32 +08:00
|
|
|
"time"
|
2020-07-26 17:09:05 +08:00
|
|
|
|
2022-01-04 15:51:32 +08:00
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
2022-06-19 17:41:33 +08:00
|
|
|
"github.com/zeromicro/go-zero/rest/chain"
|
2022-01-04 15:51:32 +08:00
|
|
|
"github.com/zeromicro/go-zero/rest/handler"
|
|
|
|
"github.com/zeromicro/go-zero/rest/httpx"
|
2023-03-11 23:15:00 +08:00
|
|
|
"github.com/zeromicro/go-zero/rest/internal"
|
2022-01-04 15:51:32 +08:00
|
|
|
"github.com/zeromicro/go-zero/rest/internal/cors"
|
2024-07-13 19:58:35 +08:00
|
|
|
"github.com/zeromicro/go-zero/rest/internal/fileserver"
|
2022-01-04 15:51:32 +08:00
|
|
|
"github.com/zeromicro/go-zero/rest/router"
|
2020-07-26 17:09:05 +08:00
|
|
|
)
|
|
|
|
|
2020-08-18 20:20:44 +08:00
|
|
|
type (
|
2021-03-01 19:15:35 +08:00
|
|
|
// RunOption defines the method to customize a Server.
|
2020-08-18 20:20:44 +08:00
|
|
|
RunOption func(*Server)
|
2020-07-26 17:09:05 +08:00
|
|
|
|
2023-03-11 23:15:00 +08:00
|
|
|
// StartOption defines the method to customize http server.
|
2023-03-12 20:42:50 +08:00
|
|
|
StartOption = internal.StartOption
|
2023-03-11 23:15:00 +08:00
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// A Server is a http server.
|
2020-08-18 20:20:44 +08:00
|
|
|
Server struct {
|
2021-11-07 22:42:40 +08:00
|
|
|
ngin *engine
|
|
|
|
router httpx.Router
|
2020-08-18 20:20:44 +08:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2020-12-25 19:47:27 +08:00
|
|
|
// MustNewServer returns a server with given config of c and options defined in opts.
|
|
|
|
// Be aware that later RunOption might overwrite previous one that write the same option.
|
|
|
|
// The process will exit if error occurs.
|
2020-08-18 20:20:44 +08:00
|
|
|
func MustNewServer(c RestConf, opts ...RunOption) *Server {
|
2021-08-14 22:57:28 +08:00
|
|
|
server, err := NewServer(c, opts...)
|
2020-08-18 20:20:44 +08:00
|
|
|
if err != nil {
|
2023-03-12 20:42:50 +08:00
|
|
|
logx.Must(err)
|
2020-08-18 20:20:44 +08:00
|
|
|
}
|
|
|
|
|
2021-08-14 22:57:28 +08:00
|
|
|
return server
|
2020-07-31 11:45:16 +08:00
|
|
|
}
|
|
|
|
|
2020-12-25 19:47:27 +08:00
|
|
|
// NewServer returns a server with given config of c and options defined in opts.
|
|
|
|
// Be aware that later RunOption might overwrite previous one that write the same option.
|
2020-08-18 20:20:44 +08:00
|
|
|
func NewServer(c RestConf, opts ...RunOption) (*Server, error) {
|
|
|
|
if err := c.SetUp(); err != nil {
|
|
|
|
return nil, err
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
2020-08-18 20:20:44 +08:00
|
|
|
|
|
|
|
server := &Server{
|
2021-11-07 22:42:40 +08:00
|
|
|
ngin: newEngine(c),
|
|
|
|
router: router.NewRouter(),
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
|
2022-02-19 20:50:33 +08:00
|
|
|
opts = append([]RunOption{WithNotFoundHandler(nil)}, opts...)
|
2020-08-18 20:20:44 +08:00
|
|
|
for _, opt := range opts {
|
|
|
|
opt(server)
|
|
|
|
}
|
2020-07-26 17:09:05 +08:00
|
|
|
|
2020-08-18 20:20:44 +08:00
|
|
|
return server, nil
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// AddRoutes add given routes into the Server.
|
2021-08-14 22:57:28 +08:00
|
|
|
func (s *Server) AddRoutes(rs []Route, opts ...RouteOption) {
|
2020-08-18 20:20:44 +08:00
|
|
|
r := featuredRoutes{
|
|
|
|
routes: rs,
|
|
|
|
}
|
|
|
|
for _, opt := range opts {
|
|
|
|
opt(&r)
|
|
|
|
}
|
2021-11-07 22:42:40 +08:00
|
|
|
s.ngin.addRoutes(r)
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// AddRoute adds given route into the Server.
|
2021-08-14 22:57:28 +08:00
|
|
|
func (s *Server) AddRoute(r Route, opts ...RouteOption) {
|
|
|
|
s.AddRoutes([]Route{r}, opts...)
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
|
2022-06-04 13:26:14 +08:00
|
|
|
// PrintRoutes prints the added routes to stdout.
|
|
|
|
func (s *Server) PrintRoutes() {
|
|
|
|
s.ngin.print()
|
|
|
|
}
|
|
|
|
|
2022-07-11 23:50:50 +08:00
|
|
|
// Routes returns the HTTP routers that registered in the server.
|
2022-07-11 23:23:38 +08:00
|
|
|
func (s *Server) Routes() []Route {
|
2022-07-11 23:50:50 +08:00
|
|
|
var routes []Route
|
|
|
|
|
2022-07-11 23:23:38 +08:00
|
|
|
for _, r := range s.ngin.routes {
|
2022-07-11 23:50:50 +08:00
|
|
|
routes = append(routes, r.routes...)
|
2022-07-11 23:23:38 +08:00
|
|
|
}
|
2022-07-11 23:50:50 +08:00
|
|
|
|
|
|
|
return routes
|
2022-07-11 23:23:38 +08:00
|
|
|
}
|
|
|
|
|
2023-01-02 13:51:15 +08:00
|
|
|
// ServeHTTP is for test purpose, allow developer to do a unit test with
|
|
|
|
// all defined router without starting an HTTP Server.
|
|
|
|
//
|
|
|
|
// For example:
|
|
|
|
//
|
|
|
|
// server := MustNewServer(...)
|
|
|
|
// server.addRoute(...) // router a
|
|
|
|
// server.addRoute(...) // router b
|
|
|
|
// server.addRoute(...) // router c
|
|
|
|
//
|
|
|
|
// r, _ := http.NewRequest(...)
|
|
|
|
// w := httptest.NewRecorder(...)
|
|
|
|
// server.ServeHTTP(w, r)
|
|
|
|
// // verify the response
|
|
|
|
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
s.ngin.bindRoutes(s.router)
|
|
|
|
s.router.ServeHTTP(w, r)
|
|
|
|
}
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// Start starts the Server.
|
2021-03-14 08:51:10 +08:00
|
|
|
// Graceful shutdown is enabled by default.
|
|
|
|
// Use proc.SetTimeToForceQuit to customize the graceful shutdown period.
|
2023-03-12 20:42:50 +08:00
|
|
|
func (s *Server) Start() {
|
|
|
|
handleError(s.ngin.start(s.router))
|
|
|
|
}
|
|
|
|
|
|
|
|
// StartWithOpts starts the Server.
|
|
|
|
// Graceful shutdown is enabled by default.
|
|
|
|
// Use proc.SetTimeToForceQuit to customize the graceful shutdown period.
|
|
|
|
func (s *Server) StartWithOpts(opts ...StartOption) {
|
|
|
|
handleError(s.ngin.start(s.router, opts...))
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// Stop stops the Server.
|
2021-08-14 22:57:28 +08:00
|
|
|
func (s *Server) Stop() {
|
2020-08-18 20:20:44 +08:00
|
|
|
logx.Close()
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// Use adds the given middleware in the Server.
|
2021-08-14 22:57:28 +08:00
|
|
|
func (s *Server) Use(middleware Middleware) {
|
|
|
|
s.ngin.use(middleware)
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// ToMiddleware converts the given handler to a Middleware.
|
2020-08-18 20:20:44 +08:00
|
|
|
func ToMiddleware(handler func(next http.Handler) http.Handler) Middleware {
|
|
|
|
return func(handle http.HandlerFunc) http.HandlerFunc {
|
|
|
|
return handler(handle).ServeHTTP
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
2020-08-18 20:20:44 +08:00
|
|
|
}
|
2020-07-26 17:09:05 +08:00
|
|
|
|
2022-06-19 17:41:33 +08:00
|
|
|
// WithChain returns a RunOption that uses the given chain to replace the default chain.
|
|
|
|
// JWT auth middleware and the middlewares that added by svr.Use() will be appended.
|
|
|
|
func WithChain(chn chain.Chain) RunOption {
|
|
|
|
return func(svr *Server) {
|
|
|
|
svr.ngin.chain = chn
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-07 22:42:40 +08:00
|
|
|
// WithCors returns a func to enable CORS for given origin, or default to all origins (*).
|
|
|
|
func WithCors(origin ...string) RunOption {
|
|
|
|
return func(server *Server) {
|
2021-11-25 23:03:37 +08:00
|
|
|
server.router.SetNotAllowedHandler(cors.NotAllowedHandler(nil, origin...))
|
2022-08-24 20:19:53 +08:00
|
|
|
server.router = newCorsRouter(server.router, nil, origin...)
|
2021-11-25 23:03:37 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// WithCustomCors returns a func to enable CORS for given origin, or default to all origins (*),
|
|
|
|
// fn lets caller customizing the response.
|
2021-11-26 14:14:06 +08:00
|
|
|
func WithCustomCors(middlewareFn func(header http.Header), notAllowedFn func(http.ResponseWriter),
|
|
|
|
origin ...string) RunOption {
|
2021-11-25 23:03:37 +08:00
|
|
|
return func(server *Server) {
|
2021-11-26 14:14:06 +08:00
|
|
|
server.router.SetNotAllowedHandler(cors.NotAllowedHandler(notAllowedFn, origin...))
|
2022-08-24 20:19:53 +08:00
|
|
|
server.router = newCorsRouter(server.router, middlewareFn, origin...)
|
2021-11-07 22:42:40 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-13 19:58:35 +08:00
|
|
|
// WithFileServer returns a RunOption to serve files from given dir with given path.
|
|
|
|
func WithFileServer(path, dir string) RunOption {
|
|
|
|
return func(server *Server) {
|
|
|
|
server.router = newFileServingRouter(server.router, path, dir)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// WithJwt returns a func to enable jwt authentication in given route.
|
2020-08-18 20:20:44 +08:00
|
|
|
func WithJwt(secret string) RouteOption {
|
|
|
|
return func(r *featuredRoutes) {
|
|
|
|
validateSecret(secret)
|
|
|
|
r.jwt.enabled = true
|
|
|
|
r.jwt.secret = secret
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// WithJwtTransition returns a func to enable jwt authentication as well as jwt secret transition.
|
2021-04-14 17:58:27 +08:00
|
|
|
// Which means old and new jwt secrets work together for a period.
|
2020-08-18 20:20:44 +08:00
|
|
|
func WithJwtTransition(secret, prevSecret string) RouteOption {
|
|
|
|
return func(r *featuredRoutes) {
|
|
|
|
// why not validate prevSecret, because prevSecret is an already used one,
|
|
|
|
// even it not meet our requirement, we still need to allow the transition.
|
|
|
|
validateSecret(secret)
|
|
|
|
r.jwt.enabled = true
|
|
|
|
r.jwt.secret = secret
|
|
|
|
r.jwt.prevSecret = prevSecret
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-31 21:39:02 +08:00
|
|
|
// WithMaxBytes returns a RouteOption to set maxBytes with the given value.
|
|
|
|
func WithMaxBytes(maxBytes int64) RouteOption {
|
|
|
|
return func(r *featuredRoutes) {
|
|
|
|
r.maxBytes = maxBytes
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// WithMiddlewares adds given middlewares to given routes.
|
2020-10-19 18:34:10 +08:00
|
|
|
func WithMiddlewares(ms []Middleware, rs ...Route) []Route {
|
|
|
|
for i := len(ms) - 1; i >= 0; i-- {
|
|
|
|
rs = WithMiddleware(ms[i], rs...)
|
|
|
|
}
|
|
|
|
return rs
|
|
|
|
}
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// WithMiddleware adds given middleware to given route.
|
2020-08-18 20:20:44 +08:00
|
|
|
func WithMiddleware(middleware Middleware, rs ...Route) []Route {
|
|
|
|
routes := make([]Route, len(rs))
|
2020-07-26 17:09:05 +08:00
|
|
|
|
2020-08-18 20:20:44 +08:00
|
|
|
for i := range rs {
|
|
|
|
route := rs[i]
|
|
|
|
routes[i] = Route{
|
|
|
|
Method: route.Method,
|
|
|
|
Path: route.Path,
|
|
|
|
Handler: middleware(route.Handler),
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-18 20:20:44 +08:00
|
|
|
return routes
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// WithNotFoundHandler returns a RunOption with not found handler set to given handler.
|
2020-10-21 14:10:29 +08:00
|
|
|
func WithNotFoundHandler(handler http.Handler) RunOption {
|
2021-11-07 22:42:40 +08:00
|
|
|
return func(server *Server) {
|
2022-02-19 20:50:33 +08:00
|
|
|
notFoundHandler := server.ngin.notFoundHandler(handler)
|
|
|
|
server.router.SetNotFoundHandler(notFoundHandler)
|
2021-11-07 22:42:40 +08:00
|
|
|
}
|
2020-10-21 14:10:29 +08:00
|
|
|
}
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// WithNotAllowedHandler returns a RunOption with not allowed handler set to given handler.
|
2020-10-21 14:10:29 +08:00
|
|
|
func WithNotAllowedHandler(handler http.Handler) RunOption {
|
2021-11-07 22:42:40 +08:00
|
|
|
return func(server *Server) {
|
|
|
|
server.router.SetNotAllowedHandler(handler)
|
|
|
|
}
|
2020-10-21 14:10:29 +08:00
|
|
|
}
|
|
|
|
|
2021-11-01 20:15:10 +08:00
|
|
|
// WithPrefix adds group as a prefix to the route paths.
|
|
|
|
func WithPrefix(group string) RouteOption {
|
|
|
|
return func(r *featuredRoutes) {
|
|
|
|
var routes []Route
|
|
|
|
for _, rt := range r.routes {
|
|
|
|
p := path.Join(group, rt.Path)
|
|
|
|
routes = append(routes, Route{
|
|
|
|
Method: rt.Method,
|
|
|
|
Path: p,
|
|
|
|
Handler: rt.Handler,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
r.routes = routes
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// WithPriority returns a RunOption with priority.
|
2020-08-18 20:20:44 +08:00
|
|
|
func WithPriority() RouteOption {
|
|
|
|
return func(r *featuredRoutes) {
|
|
|
|
r.priority = true
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// WithRouter returns a RunOption that make server run with given router.
|
2020-08-18 20:20:44 +08:00
|
|
|
func WithRouter(router httpx.Router) RunOption {
|
|
|
|
return func(server *Server) {
|
2021-11-07 22:42:40 +08:00
|
|
|
server.router = router
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// WithSignature returns a RouteOption to enable signature verification.
|
2020-08-18 20:20:44 +08:00
|
|
|
func WithSignature(signature SignatureConf) RouteOption {
|
|
|
|
return func(r *featuredRoutes) {
|
|
|
|
r.signature.enabled = true
|
|
|
|
r.signature.Strict = signature.Strict
|
|
|
|
r.signature.Expiry = signature.Expiry
|
|
|
|
r.signature.PrivateKeys = signature.PrivateKeys
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-03 22:20:32 +08:00
|
|
|
// WithTimeout returns a RouteOption to set timeout with given value.
|
|
|
|
func WithTimeout(timeout time.Duration) RouteOption {
|
|
|
|
return func(r *featuredRoutes) {
|
|
|
|
r.timeout = timeout
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-31 14:10:47 +08:00
|
|
|
// WithTLSConfig returns a RunOption that with given tls config.
|
|
|
|
func WithTLSConfig(cfg *tls.Config) RunOption {
|
2022-03-04 17:54:09 +08:00
|
|
|
return func(svr *Server) {
|
|
|
|
svr.ngin.setTlsConfig(cfg)
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
2020-08-18 20:20:44 +08:00
|
|
|
}
|
2020-07-26 17:09:05 +08:00
|
|
|
|
2021-10-31 14:10:47 +08:00
|
|
|
// WithUnauthorizedCallback returns a RunOption that with given unauthorized callback set.
|
|
|
|
func WithUnauthorizedCallback(callback handler.UnauthorizedCallback) RunOption {
|
2022-03-04 17:54:09 +08:00
|
|
|
return func(svr *Server) {
|
|
|
|
svr.ngin.setUnauthorizedCallback(callback)
|
2021-10-31 12:56:25 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// WithUnsignedCallback returns a RunOption that with given unsigned callback set.
|
2020-08-18 20:20:44 +08:00
|
|
|
func WithUnsignedCallback(callback handler.UnsignedCallback) RunOption {
|
2022-03-04 17:54:09 +08:00
|
|
|
return func(svr *Server) {
|
|
|
|
svr.ngin.setUnsignedCallback(callback)
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
2020-08-18 20:20:44 +08:00
|
|
|
}
|
2020-07-26 17:09:05 +08:00
|
|
|
|
2020-08-18 20:20:44 +08:00
|
|
|
func handleError(err error) {
|
|
|
|
// ErrServerClosed means the server is closed manually
|
2023-10-21 00:00:57 +08:00
|
|
|
if err == nil || errors.Is(err, http.ErrServerClosed) {
|
2020-08-18 20:20:44 +08:00
|
|
|
return
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
|
2020-08-18 20:20:44 +08:00
|
|
|
logx.Error(err)
|
|
|
|
panic(err)
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
|
2020-08-18 20:20:44 +08:00
|
|
|
func validateSecret(secret string) {
|
|
|
|
if len(secret) < 8 {
|
|
|
|
panic("secret's length can't be less than 8")
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
}
|
2022-08-24 20:19:53 +08:00
|
|
|
|
|
|
|
type corsRouter struct {
|
|
|
|
httpx.Router
|
|
|
|
middleware Middleware
|
|
|
|
}
|
|
|
|
|
|
|
|
func newCorsRouter(router httpx.Router, headerFn func(http.Header), origins ...string) httpx.Router {
|
|
|
|
return &corsRouter{
|
|
|
|
Router: router,
|
|
|
|
middleware: cors.Middleware(headerFn, origins...),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *corsRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
c.middleware(c.Router.ServeHTTP)(w, r)
|
|
|
|
}
|
2024-07-13 19:58:35 +08:00
|
|
|
|
|
|
|
type fileServingRouter struct {
|
|
|
|
httpx.Router
|
|
|
|
middleware Middleware
|
|
|
|
}
|
|
|
|
|
|
|
|
func newFileServingRouter(router httpx.Router, path, dir string) httpx.Router {
|
|
|
|
return &fileServingRouter{
|
|
|
|
Router: router,
|
|
|
|
middleware: fileserver.Middleware(path, dir),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *fileServingRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
f.middleware(f.Router.ServeHTTP)(w, r)
|
|
|
|
}
|