首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Gorilla Mux路由未解析

Gorilla Mux路由未解析
EN

Stack Overflow用户
提问于 2016-01-21 05:32:29
回答 1查看 2.4K关注 0票数 1

因此,我正在使用Go和Gorilla Mux开发一个简单的RESTful应用程序接口。我遇到了我的第二个路由不工作的问题,它返回了一个404错误。我不确定问题出在哪里,因为我是新来Go和Gorilla的。我确定这是很简单的东西,但是我好像找不到了。我认为这可能是一个问题,因为我使用了不同的自定义包。

这个问题是相似的,Routes returning 404 for mux gorilla,但是被接受的解决方案没有解决我的问题

下面是我的代码:

Router.go:

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
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,
    },
}
EN

回答 1

Stack Overflow用户

发布于 2016-01-21 22:24:43

我的项目似乎保留了主src目录中的Router.go和Handlers.go文件的旧版本。通过删除这些重复文件并使用go run Main.go重新运行Main.go,我能够使路由被识别。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34910997

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档