因此,我正在使用Go和Gorilla Mux开发一个简单的RESTful应用程序接口。我遇到了我的第二个路由不工作的问题,它返回了一个404错误。我不确定问题出在哪里,因为我是新来Go和Gorilla的。我确定这是很简单的东西,但是我好像找不到了。我认为这可能是一个问题,因为我使用了不同的自定义包。
这个问题是相似的,Routes returning 404 for mux gorilla,但是被接受的解决方案没有解决我的问题
下面是我的代码:
Router.go:
package router
import (
"github.com/gorilla/mux"
"net/http"
)
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(route.HandlerFunc)
}
return router
}
var routes = Routes{
Route{
"CandidateList",
"GET",
"/candidate",
CandidateList,
},
Route{
"Index",
"GET",
"/",
Index,
},
}Handlers.go
package router
import (
"fmt"
"net/http"
)
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Welcome!")
}
func CandidateList(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "CandidateList!")
}Main.go
package main
import (
"./router"
"log"
"net/http"
)
func main() {
rout := router.NewRouter()
log.Fatal(http.ListenAndServe(":8080", rout))
}转到localhost:8080返回Welcome!但是转到localhost:8080/candidate会返回一个404 Page Not Found错误。我非常感谢大家的投入和帮助!谢谢!
这是我的Router.go文件的更新版本,仍然存在相同的问题。
Router.go
package router
import (
"github.com/gorilla/mux"
"net/http"
)
type Route struct {
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Handler(route.HandlerFunc).GetError()
}
return router
}
var routes = Routes{
Route{
"GET",
"/candidate",
CandidateList,
},
Route{
"GET",
"/",
Index,
},
}发布于 2016-01-21 22:24:43
我的项目似乎保留了主src目录中的Router.go和Handlers.go文件的旧版本。通过删除这些重复文件并使用go run Main.go重新运行Main.go,我能够使路由被识别。
https://stackoverflow.com/questions/34910997
复制相似问题