71 lines
2.2 KiB
Go
71 lines
2.2 KiB
Go
// Package gin adapts Gin to GoOmni's transport-neutral router contract.
|
|
// Business packages should import httpx and app, not this package.
|
|
package gin
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"git.yuntuo.hk/k2safe/go-omni/httpx"
|
|
ginlib "github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// Router is the default Gin-backed GoOmni router.
|
|
type Router struct {
|
|
engine *ginlib.Engine
|
|
}
|
|
|
|
// New creates a Gin router without Gin's default logger or recovery middleware.
|
|
func New(mode string) *Router {
|
|
if mode != "" {
|
|
ginlib.SetMode(mode)
|
|
}
|
|
return &Router{engine: ginlib.New()}
|
|
}
|
|
|
|
// NewWithEngine wraps an existing Gin engine for incremental migration.
|
|
func NewWithEngine(engine *ginlib.Engine) *Router { return &Router{engine: engine} }
|
|
|
|
// Engine exposes the underlying Gin engine to adapter-specific integrations.
|
|
func (r *Router) Engine() *ginlib.Engine { return r.engine }
|
|
|
|
func (r *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
|
r.engine.ServeHTTP(writer, request)
|
|
}
|
|
|
|
func (r *Router) Handle(method, path string, handler http.Handler) {
|
|
r.engine.Handle(method, path, r.adapt(handler))
|
|
}
|
|
|
|
func (r *Router) Any(path string, handler http.Handler) { r.engine.Any(path, r.adapt(handler)) }
|
|
|
|
func (r *Router) Group(path string) httpx.RouterGroup {
|
|
return &group{group: r.engine.Group(path)}
|
|
}
|
|
|
|
type group struct{ group *ginlib.RouterGroup }
|
|
|
|
func (g *group) Handle(method, path string, handler http.Handler) {
|
|
g.group.Handle(method, path, adapt(handler))
|
|
}
|
|
|
|
func (g *group) Any(path string, handler http.Handler) { g.group.Any(path, adapt(handler)) }
|
|
|
|
func (g *group) Group(path string) httpx.RouterGroup {
|
|
return &group{group: g.group.Group(path)}
|
|
}
|
|
|
|
func (r *Router) adapt(handler http.Handler) ginlib.HandlerFunc { return adapt(handler) }
|
|
|
|
func adapt(handler http.Handler) ginlib.HandlerFunc {
|
|
return func(ctx *ginlib.Context) {
|
|
params := make(map[string]string, len(ctx.Params))
|
|
for _, param := range ctx.Params {
|
|
params[param.Key] = param.Value
|
|
}
|
|
requestContext := httpx.WithRouteParams(ctx.Request.Context(), params)
|
|
requestContext = httpx.WithRoutePattern(requestContext, ctx.FullPath())
|
|
request := ctx.Request.WithContext(requestContext)
|
|
handler.ServeHTTP(ctx.Writer, request)
|
|
}
|
|
}
|