dongtang3155 2015-04-30 16:58
浏览 140
已采纳

Golang Gorilla Mux,匹配两个URL签名的最佳方法

Using gorilla mux, I currently have many URLs that are of the form:

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

such that the code looks like:

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

I'd like to also match against:

subdomain.domain.com/{name}/pagename

I know I can do something like

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

to match on the subdomain. Is it possible to only have one HandleFunc() that will match both types of URLs, or do I need to have two HandleFunc()s, one for the first case and one for the subdomain.domain.com case?

  • 写回答

1条回答 默认 最新

  • douzhimao8656 2015-04-30 20:35
    关注

    With a dispatcher like this you only have to add one line per 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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大