0

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

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

这样代码看起来像:

rtr.HandleFunc("/org/{subdomain}/{name}/promote", promoteView)

我还想匹配:

subdomain.domain.com/{name}/pagename

我知道我可以做类似的事情

rtr.Host("{subdomain:[a-z]+}.domain.com").HandleFunc("/{name}/promote", promoteView)

在子域上匹配。是否可能只有一个 HandleFunc() 可以匹配两种类型的 URL,或者我是否需要两个 HandleFunc(),一个用于第一种情况,一个用于 subdomain.domain.com 情况?

4

1 回答 1

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)
}
于 2015-04-30T20:35:33.543 回答