Gorilla Mux无法处理我的路径。

huangapple go评论84阅读模式
英文:

Gorilla Mux not handling my path

问题

当我使用http的默认路由器时,一切正常工作,但如果我使用gorilla/mux的路由器,我会得到一个带有内容为404 page not found的404页面。如下面的示例所示,其他部分完全相同。

为什么gorilla/mux的路由器不像这样工作?

使用http路由器正确工作的示例:

package main

import "net/http"

func simplestPossible(w http.ResponseWriter, req *http.Request) {
    w.Write([]byte("MWE says OK"))
}

func main() {
    http.HandleFunc("/", simplestPossible)

    http.ListenAndServe(":8000", nil)
}

使用gorilla/mux路由器不工作的示例:

package main

import "net/http"
import "github.com/gorilla/mux"

func simplestPossible(w http.ResponseWriter, req *http.Request) {
    w.Write([]byte("MWE says OK"))
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", simplestPossible)

    http.ListenAndServe(":8000", nil)
}
英文:

When I use the default router from http everything works, but if I use the router from gorilla/mux instead, I get a 404 page with the body 404 page not found. As shown in the samples below, everything else is exactly the same.

Why doesn't the gorilla/mux router work like this?

Working correctly, using http routing:

package main

import "net/http"

func simplestPossible(w http.ResponseWriter, req *http.Request) {
	w.Write([]byte("MWE says OK"))
}

func main() {
	http.HandleFunc("/", simplestPossible)

	http.ListenAndServe(":8000", nil)
}

Not working, using gorilla/mux routing:

package main

import "net/http"
import "github.com/gorilla/mux"

func simplestPossible(w http.ResponseWriter, req *http.Request) {
	w.Write([]byte("MWE says OK"))
}

func main() {
    r := mux.NewRouter()
	r.HandleFunc("/", simplestPossible)

	http.ListenAndServe(":8000", nil)
}

答案1

得分: 2

你必须将你的处理程序传递给http包的ListenAndServe函数:

http.ListenAndServe(":8000", r)
英文:

You must pass your handler to http package (ListenAndServe):

<!-- language: go -->

http.ListenAndServe(&quot;:8000&quot;, r)

huangapple
  • 本文由 发表于 2017年4月29日 00:14:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/43684679.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定