60 lines
1.2 KiB
Go
60 lines
1.2 KiB
Go
/*
|
||
router.go - 路由管理
|
||
实现了HTTP路由和中间件管理功能
|
||
*/
|
||
|
||
package server
|
||
|
||
import (
|
||
"net/http"
|
||
|
||
"github.com/gorilla/mux"
|
||
)
|
||
|
||
// Router 路由器结构体
|
||
type Router struct {
|
||
*mux.Router
|
||
}
|
||
|
||
// NewRouter 创建新的路由器
|
||
func NewRouter() *Router {
|
||
return &Router{
|
||
Router: mux.NewRouter(),
|
||
}
|
||
}
|
||
|
||
// Use 添加中间件
|
||
func (r *Router) Use(middleware func(http.Handler) http.Handler) {
|
||
r.Router.Use(middleware)
|
||
}
|
||
|
||
// Methods 设置HTTP方法(链式调用)
|
||
func (r *Router) Methods(methods ...string) *mux.Route {
|
||
return r.Router.Methods(methods...)
|
||
}
|
||
|
||
// PathPrefix 路径前缀
|
||
func (r *Router) PathPrefix(tpl string) *mux.Router {
|
||
return r.Router.PathPrefix(tpl)
|
||
}
|
||
|
||
// Subrouter 创建子路由
|
||
func (r *Router) Subrouter() *mux.Router {
|
||
return r.Router.NewRoute().Subrouter()
|
||
}
|
||
|
||
// HandleFunc 处理函数路由
|
||
func (r *Router) HandleFunc(path string, f func(http.ResponseWriter, *http.Request)) *mux.Route {
|
||
return r.Router.HandleFunc(path, f)
|
||
}
|
||
|
||
// Handle 处理器路由
|
||
func (r *Router) Handle(path string, handler http.Handler) *mux.Route {
|
||
return r.Router.Handle(path, handler)
|
||
}
|
||
|
||
// ServeHTTP 实现http.Handler接口
|
||
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||
r.Router.ServeHTTP(w, req)
|
||
}
|