Http 为mux gorilla返回404的路线

Http 为mux gorilla返回404的路线,http,go,Http,Go,在我的Go应用程序中,我使用的是gorilla/mux 我想要 http://host:3000/从子目录“frontend”和 http://host:3000/api/及其子路径由指定函数提供服务 对于以下代码,两个调用都不起作用。 /index.html是唯一一个不支持的(但不是它加载的资源)。我做错了什么 package main import ( "log" "net/http" "fmt" "strconv" "github.com/gorilla/mux" )

在我的Go应用程序中,我使用的是gorilla/mux

我想要

http://host:3000/
从子目录“frontend”
http://host:3000/api/
及其子路径由指定函数提供服务

对于以下代码,两个调用都不起作用。
/index.html
是唯一一个不支持的(但不是它加载的资源)。我做错了什么

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)
}
主程序包
进口(
“日志”
“net/http”
“fmt”
“strconv”
“github.com/gorilla/mux”
)
func main(){
routineQuit:=make(chan int)
路由器:=mux.NewRouter().StrictSlash(真)
router.PathPrefix(“/”)处理程序(http.FileServer(http.Dir(“./frontend/”))
router.HandleFunc(“/api”,索引)
路由器.HandleFunc(“/api/abc”,AbcIndex)
router.HandleFunc(“/api/abc/{id}”,AbcShow)
http.Handle(“/”,路由器)
http.ListenAndServe(“:”+strconv.Itoa(3000),路由器)

Gorilla的mux路由按照添加顺序进行评估。因此,将使用与请求匹配的第一条路由

在您的情况下,
/
处理程序将匹配每个传入的请求,然后在
frontend/
目录中查找该文件,然后显示404错误。您只需交换路由以使其运行:

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)

这救了我!我的头跟着各种各样的线索,想知道发生了什么事。谢谢