CGideon
CGideon

Reputation: 143

Gorilla Mux routes not resolving

So, I'm working on a simple RESTful API using Go and Gorilla Mux. I'm having issues with with my second route not working, it's returning a 404 error. I'm not sure what the problem is as I'm new to Go and Gorilla. I'm sure it's something really simple, but I can't seem to find it. I think it might be a problem with the fact that I'm using different custom packages.

This question is similar, Routes returning 404 for mux gorilla, but the accepted solution didn't fix my problem

Here's what my code looks like:

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

Going to just localhost:8080 returns Welcome! but going to localhost:8080/candidate returns a 404 Page Not Found error. I appreciate any input and help! Thanks!

This is an updated version of my Router.go file, there is still the same issue happening.

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

Upvotes: 1

Views: 3261

Answers (1)

CGideon
CGideon

Reputation: 143

It appears that my project was holding onto old versions of the Router.go and Handlers.go files in the main src directory. By removing these duplicate files and re-running Main.go with go run Main.go I was able to get the route to be recognized.

Upvotes: 1

Related Questions