Golang Gorilla mux,匹配两个 url 签名的最佳方式

Golang Gorilla mux, best way to match against two url signatures

使用 gorilla mux,我目前有许多形式为以下形式的 URL:

domain.com/org/{subdomain}/{name}/pagename

代码如下所示:

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 情况?

使用这样的调度程序,您只需为每个 router/handler 添加一行。

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