Files
golang/golang-learning/10-projects/03-web-server/server/router.go
2025-08-24 13:01:09 +08:00

60 lines
1.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
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)
}