我想在gorilla/mux
路由和路由器类型上添加一个便捷的util方法:
package util
import(
"net/http"
"github.com/0xor1/gorillaseed/src/server/lib/mux"
)
func (r *mux.Route) Subroute(tpl string, h http.Handler) *mux.Route{
return r.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h)
}
func (r *mux.Router) Subroute(tpl string, h http.Handler) *mux.Route{
return r.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h)
}
但是编译器告诉我
无法在非本地类型mux.Router上定义新方法
那么我将如何实现呢?是否创建具有匿名mux.Route和mux.Router字段的新结构类型?或者是其他东西?
最佳答案
正如编译器所提到的,您不能在另一个包中扩展现有类型。您可以定义自己的别名或子包,如下所示:
type MyRouter mux.Router
func (m *MyRouter) F() { ... }
或嵌入原始路由器:
type MyRouter struct {
*mux.Router
}
func (m *MyRouter) F() { ... }
...
r := &MyRouter{router}
r.F()
关于go - 如何在Go中向现有类型添加新方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63881662/