2015-04-30 16:58
浏览 84

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

Using gorilla mux, I currently have many URLs that are of the form:{subdomain}/{name}/pagename

such that the code looks like:

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

I'd like to also match against:{name}/pagename

I know I can do something like

rtr.Host("{subdomain:[a-z]+}").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 case?

图片转代码服务由CSDN问答提供 功能建议

我目前使用大猩猩复用器,其中有许多URL的形式为: < p> {subdomain} / {name} / pagename


  rtr  .HandleFunc(“ / org / {subdomain} / {name} / promote”,PromotionView)

我也想与以下项进行匹配: {name} / pagename


   rtr.Host(“ {subdomain:[az] +}。”)。HandleFunc(“ / {name} / promote”,PromotionView)

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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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 (
    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)
        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)
        http.ListenAndServe(":8080", r)
    打赏 评论

相关推荐 更多相似问题