看来您已经接受了答案,但我想提出一个替代解决方案。
我质疑添加自定义复用器的必要性。在这个例子中,我使用了 gorilla muxer,但这只是因为我熟悉它的模式匹配。理论上,您可以匹配传入 URL 中的模式,而无需替换默认的 muxer。
我的代码在映射中维护处理程序函数(字符串:处理程序名称 => 函数字面量)...这适合使用默认的 muxers HandleFunc 方法。
样本输入/输出:
获取/注册/123
获取 /123
hello from123.
获取/销毁/123
获取 /123
[nothing]
package main
import (
"code.google.com/p/gorilla/mux"
"flag"
"log"
"net/http"
)
// Wraps server muxer, dynamic map of handlers, and listen port.
type Server struct {
Dispatcher *mux.Router
Urls map[string]func(w http.ResponseWriter, r *http.Request)
Port string
}
// May the signal never stop.
func main() {
//Initialize Server
server := &Server{Port: "3000", Dispatcher: mux.NewRouter(), Urls: make(map[string]func(w http.ResponseWriter, r *http.Request))}
var port = flag.String("port", "3000", "Default: 3000; Set the port for the web-server to accept incoming requests")
flag.Parse()
server.Port = *port
log.Printf("Starting server on port: %s \n", server.Port)
server.InitDispatch()
log.Printf("Initializing request routes...\n")
server.Start() //Launch server; blocks goroutine.
}
func (s *Server) Start() {
http.ListenAndServe(":"+s.Port, s.Dispatcher)
}
// Initialize Dispatcher's routes.
func (s *Server) InitDispatch() {
d := s.Dispatcher
// Add handler to server's map.
d.HandleFunc("/register/{name}", func(w http.ResponseWriter, r *http.Request) {
//somewhere somehow you create the handler to be used; i'll just make an echohandler
vars := mux.Vars(r)
name := vars["name"]
s.AddFunction(w, r, name)
}).Methods("GET")
d.HandleFunc("/destroy/{name}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
name := vars["name"]
s.Destroy(name)
}).Methods("GET")
d.HandleFunc("/{name}", func(w http.ResponseWriter, r *http.Request) {
//Lookup handler in map and call it, proxying this writer and request
vars := mux.Vars(r)
name := vars["name"]
s.ProxyCall(w, r, name)
}).Methods("GET")
}
func (s *Server) Destroy(fName string) {
s.Urls[fName] = nil //remove handler
}
func (s *Server) ProxyCall(w http.ResponseWriter, r *http.Request, fName string) {
if s.Urls[fName] != nil {
s.Urls[fName](w, r) //proxy the call
}
}
func (s *Server) AddFunction(w http.ResponseWriter, r *http.Request, fName string) {
f := func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello from" + fName))
}
s.Urls[fName] = f // Add the handler to our map
}