完成
This commit is contained in:
59
golang-learning/10-projects/03-web-server/server/router.go
Normal file
59
golang-learning/10-projects/03-web-server/server/router.go
Normal file
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
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)
|
||||
}
|
Reference in New Issue
Block a user