dri8163 2015-03-03 11:54
浏览 20
已采纳

返回404的多路复用大猩猩路线

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条回答 默认 最新

  • dongwen9051 2015-03-03 12:24
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测