【问题标题】:gorilla mux router handlersgorilla mux 路由器处理程序
【发布时间】:2014-09-28 16:14:20
【问题描述】:

我无法让 gorilla mux 工作..

当请求http://www.localhost:9000 时,Web 服务器会返回 404 page not found

但这工作 http://localhost:9000/ 并打印 Hello world

package main

import (
    "net/http"
    "fmt"
    "log"
    "github.com/gorilla/mux"
)

func Handler(w http.ResponseWriter, r *http.Request){
    fmt.Fprint(w, "Hello world")
}

func main(){
    r := mux.NewRouter()
    r.Host("www.localhost")
    r.HandleFunc("/", Handler)
    err := http.ListenAndServe(":9000", r)
    if err != nil {
        log.Fatal("ListenAndServe error: ", err)
    }
}

【问题讨论】:

  • /etc/hosts 已设置.. 网络服务器响应 www.localhost404

标签: go mux


【解决方案1】:

您希望能够同时支持 localhost 和 www.localhost

package main

import (
        "fmt"
        "log"
        "net/http"

        "github.com/gorilla/mux"
)

func Handler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, "Hello world")
}

func main() {
        r := mux.NewRouter()
        r.Host("www.localhost").Path("/").HandlerFunc(Handler)
        r.HandleFunc("/", Handler)
        err := http.ListenAndServe(":9000", r)
        if err != nil {
                log.Fatal("ListenAndServe error: ", err)
        }
}

如果您仔细阅读文档,您会注意到 r.Host() 只是另一个模式匹配函数。它没有为该路由器设置任何全局规则。

如果您想让该规则被继承,您需要使用子路由器:

subrouter := r.Host("www.localhost").Subrouter()

然后你用“subrouter”代替“r”

【讨论】:

    猜你喜欢
    • 2017-09-22
    • 2014-12-22
    • 2014-09-08
    • 2016-04-07
    • 2017-11-07
    • 2020-08-26
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    相关资源
    最近更新 更多