Routes returning 404 for mux gorilla

2019-08-15 17:20发布

问题:

In my Go application, I'm using gorilla/mux.

I would like to have

http://host:3000/ to be serving files statically from the subdirectory "frontend" and http://host:3000/api/ and its subpaths being served by the specified functions.

With the following code, neither of the calls work. /index.html is the only one that doesn (but not the resources being loaded by it). What am I doing wrong?

package main

import (
  "log"
  "net/http"
  "fmt"
  "strconv"
  "github.com/gorilla/mux"
)

func main() {
  routineQuit := make(chan int)

  router := mux.NewRouter().StrictSlash(true)
  router.PathPrefix("/").Handler(http.FileServer(http.Dir("./frontend/")))
  router.HandleFunc("/api", Index)
  router.HandleFunc("/api/abc", AbcIndex)
  router.HandleFunc("/api/abc/{id}", AbcShow)
  http.Handle("/", router)
  http.ListenAndServe(":" + strconv.Itoa(3000), router)

  <- routineQuit
}

func Abc(w http.ResponseWriter, r *http.Request) {
  fmt.Fprintln(w, "Index!")
}

func AbcIndex(w http.ResponseWriter, r *http.Request) {
  fmt.Fprintln(w, "Todo Index!")
}

func AbcShow(w http.ResponseWriter, r *http.Request) {
  vars := mux.Vars(r)
  todoId := vars["todoId"]
  fmt.Fprintln(w, "Todo show:", todoId)
}

回答1:

Gorilla's mux routes are evaluated in the order in which they are added. Therefore, the first route to match the request is used.

In your case, the / handler will match every incoming request, then look for the file in the frontend/ directory, then display a 404 error. You just need to swap your routes order to get it running:

router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/api/abc/{id}", AbcShow)
router.HandleFunc("/api/abc", AbcIndex)
router.HandleFunc("/api", Abc)
router.PathPrefix("/").Handler(http.FileServer(http.Dir("./frontend/")))
http.Handle("/", router)


标签: http go