golang mux HandleFunc总是404

时间:2015-06-02 16:25:15

标签: http go

由于原因,我尝试使用mux而不是net / http的标准HandleFunc来处理HTTP请求。使用http它曾经工作,与多普勒它没有。

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)
}

以下POST请求

localhost:8080/poll

结果:

INFO     2015-06-02 16:23:12,219 module.py:718] default: "POST /poll HTTP/1.1" 404 19

2 个答案:

答案 0 :(得分:1)

找到解决方案。

更改

http.ListenAndServe(":8080", mx)

http.Handle("/", mx)

答案 1 :(得分:0)

您忘记添加默认处理程序。最好将方法与处理程序一起保留。

 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)
}