英文:
golang mux HandleFunc always 404
问题
我尝试使用mux来处理HTTP请求,而不是使用net/http中的标准HandleFunc,因为有一些原因。在使用http时它可以工作,但在使用mux时却不能。
import (
    _ "github.com/go-sql-driver/mysql"
    "github.com/gorilla/mux"
    _ "io/ioutil"
    "net/http"
)
func init() {
    mx := mux.NewRouter()
    // 创建一个投票
    mx.HandleFunc("/poll", pollCreate)
    mx.HandleFunc("/poll/{id}", loadPoll)
    mx.HandleFunc("/poll/vote", castVote)
    http.ListenAndServe(":8080", mx)
}
发送以下POST请求:
localhost:8080/poll
结果为:
INFO     2015-06-02 16:23:12,219 module.py:718] default: "POST /poll HTTP/1.1" 404 19
英文:
I try to handle HTTP request using mux instead of standart HandleFunc from net/http, because of reasons. With http it used to work, with mux it doesnt.
import (
    _ "github.com/go-sql-driver/mysql"
    "github.com/gorilla/mux"
    _ "io/ioutil"
    "net/http"
)
func init() {
    mx := mux.NewRouter()
    //create a poll
    mx.HandleFunc("/poll", pollCreate)
    mx.HandleFunc("/poll/{id}", loadPoll)
    mx.HandleFunc("/poll/vote", castVote)
    http.ListenAndServe(":8080", mx)
}
The following POST request
localhost:8080/poll
Results in:
INFO     2015-06-02 16:23:12,219 module.py:718] default: "POST /poll HTTP/1.1" 404 19
答案1
得分: 3
找到解决方案。
将
http.ListenAndServe(":8080", mx)
改为
http.Handle("/", mx)
英文:
Found solution.
Change
http.ListenAndServe(":8080", mx)
To
http.Handle("/", mx)
答案2
得分: 0
你忘记添加默认处理程序了。最好将方法与处理程序一起保留。
import (
    _ "github.com/go-sql-driver/mysql"
    "github.com/gorilla/mux"
    _ "io/ioutil"
    "net/http"
)
func init() {
    mx := mux.NewRouter()
    // 创建一个投票
    mx.Path("/").HandlerFunc(indexHandler)
    mx.PathPrefix("/poll").Handler(pollCreate).Method("POST")
    mx.PathPrefix("/poll/{id}").Handler(loadPoll)
    mx.PathPrefix("/poll/vote").Handler(castVote)
    http.ListenAndServe(":8080", mx)
}
英文:
You forgot to add the default handler. It's always better to keep the method along with the handlers.
 import (
        _ "github.com/go-sql-driver/mysql"
        "github.com/gorilla/mux"
        _ "io/ioutil"
        "net/http"
    )
func init() {
    mx := mux.NewRouter()
    //create a poll
    mx.Path("/").HandlerFunc(indexHandler)
    mx.PathPrefix("/poll", pollCreate).Method("POST)
    mx.PathPrefix("/poll/{id}", loadPoll)
    mx.PathPrefix("/poll/vote", castVote)
    http.ListenAndServe(":8080", mx)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论