修复(#105): 消除 goctl 重新生成漂移
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
package rest
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
type Middleware = gin.HandlerFunc
|
||||
|
||||
type Route struct {
|
||||
Method string
|
||||
Path string
|
||||
Handler gin.HandlerFunc
|
||||
Middlewares []Middleware
|
||||
}
|
||||
|
||||
type RouteOption func(*routeOptions)
|
||||
|
||||
type routeOptions struct {
|
||||
prefix string
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
router *gin.Engine
|
||||
optionalAuth Middleware
|
||||
}
|
||||
|
||||
type ServerOption func(*Server)
|
||||
|
||||
func NewServer(router *gin.Engine, opts ...ServerOption) *Server {
|
||||
server := &Server{router: router}
|
||||
for _, opt := range opts {
|
||||
opt(server)
|
||||
}
|
||||
return server
|
||||
}
|
||||
|
||||
func WithOptionalAuth(middleware Middleware) ServerOption {
|
||||
return func(server *Server) {
|
||||
server.optionalAuth = middleware
|
||||
}
|
||||
}
|
||||
|
||||
func WithMiddlewares(middlewares []Middleware, routes ...Route) []Route {
|
||||
for i := range routes {
|
||||
routes[i].Middlewares = append(routes[i].Middlewares, middlewares...)
|
||||
}
|
||||
return routes
|
||||
}
|
||||
|
||||
func WithPrefix(prefix string) RouteOption {
|
||||
return func(opts *routeOptions) {
|
||||
opts.prefix = prefix
|
||||
}
|
||||
}
|
||||
|
||||
func WithJwt(_ string) RouteOption {
|
||||
return func(_ *routeOptions) {}
|
||||
}
|
||||
|
||||
func (server *Server) AddRoutes(routes []Route, opts ...RouteOption) {
|
||||
options := routeOptions{}
|
||||
for _, opt := range opts {
|
||||
opt(&options)
|
||||
}
|
||||
|
||||
for _, route := range routes {
|
||||
handlers := append([]gin.HandlerFunc{}, route.Middlewares...)
|
||||
if server.optionalAuth != nil && options.prefix == "/v1/public/subscribe" && route.Path == "/list" && len(handlers) > 0 {
|
||||
handlers[0] = server.optionalAuth
|
||||
}
|
||||
handlers = append(handlers, route.Handler)
|
||||
server.router.Handle(route.Method, options.prefix+route.Path, handlers...)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user