使用gorilla mux,我目前有许多以下格式的网址:
domain.com/org/ {子域} / {名称} /页面名称
使代码看起来像:
rtr.HandleFunc("/org/{subdomain}/{name}/promote", promoteView)
我也希望与之匹敌:
subdomain.domain.com/ {名称} /页面名称
我知道我可以做类似
的事情rtr.Host("{subdomain:[a-z]+}.domain.com").HandleFunc("/{name}/promote", promoteView)
在子域上匹配。是否可以只有一个HandleFunc()匹配两种类型的URL,或者我需要有两个HandleFunc(),一个用于第一个案例,一个用于subdomain.domain.com案例?
答案 0 :(得分:1)
使用这样的调度程序,您只需为每个路由器/处理程序添加一行。
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
type key struct {
subdomain, name string
}
type dispatcher map[key]http.Handler
func (d dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
handler, ok := d[key{vars["subdomain"], vars["name"]}]
if ok {
handler.ServeHTTP(w, r)
return
}
http.NotFound(w, r)
}
func handleA(rw http.ResponseWriter, req *http.Request) {
fmt.Fprintln(rw, "handleA serving")
}
func handleB(rw http.ResponseWriter, req *http.Request) {
fmt.Fprintln(rw, "handleB serving")
}
var Dispatcher = dispatcher{
key{"subA", "nameA"}: http.HandlerFunc(handleA),
key{"subB", "nameB"}: http.HandlerFunc(handleB),
// add your new routes here
}
func main() {
r := mux.NewRouter()
r.Handle("/org/{subdomain}/{name}/promote", Dispatcher)
r.Host("{subdomain:[a-z]+}.domain.com").Path("/{name}/promote").Handler(Dispatcher)
http.ListenAndServe(":8080", r)
}