2015-03-03 156 views
1

在我的Go应用中,我正在使用大猩猩/多路复用器。为多路复用器大猩猩返回404的路由

我想有

http://host:3000/静态地从子目录“前端” 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) 
} 

回答

2

大猩猩的多路复用器路由按它们的添加顺序进行评估。因此,使用匹配请求的第一条路由。

在你的情况下,/处理程序将匹配每个传入请求,然后查找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) 
+0

Ouch。这工作!谢谢。 – Atmocreations 2015-03-03 12:39:11

+0

这救了我!按照所有类型的线索来帮助我的脑袋,想知道发生了什么。谢谢 – MarsAndBack 2017-12-05 22:53:54