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,
},
}
err := router.Methods(route.Method).Path(route.Pattern).Name(route.Name).Handler(route.HandlerFunc).GetError()
– abm.Name()
function call when registering the routes.. try doing that and make sure you are not caching the responses. – abmerr := router.Methods()...GetError()
and check if it returns an errorif err != nil{ log.Println(err) }
– abm