golang mux HandleFunc 总是返回 404 错误。

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

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

huangapple
  • 本文由 发表于 2015年6月3日 00:25:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/30601495.html
匿名

发表评论

匿名网友

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

确定