2015-03-03 73 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

相關問題