"空白回复" NotFoundHandler不工作大猩猩

时间:2014-12-15 03:28:49

标签: go

我正在尝试通过编写自定义未找到的处理程序来调试404-not-found。这是我的代码。

package main

import (
  "database/sql"
  "encoding/json"
  "fmt"
  "log"
  "net/http"

  "github.com/coopernurse/gorp"
  _ "github.com/go-sql-driver/mysql"
  "github.com/gorilla/mux"
)

func main() {

  // Create a MUX
  r := mux.NewRouter()
  http.Handle("/", r)
  r.NotFoundHandler = http.HandlerFunc(NotFound)

  // Static
  r.PathPrefix("/app").HandlerFunc(uiAppHandler)
  err := http.ListenAndServe(":8080", nil)
  if err != nil {
    log.Fatal(err)
  }
}

func NotFound(w http.ResponseWriter, r *http.Request) {
  fmt.Fprint(w, "custom 404")
}

func uiAppHandler(w http.ResponseWriter, r *http.Request) {
  repoFrontend1 := "/UI/KD/WebContent"
  http.StripPrefix("/app/", http.FileServer(http.Dir(repoFrontend1)))
}

我对现有和未存在的文件都收到空白回复。我猜NotFound没有被触发,因为我的" /"处理程序。那么如何处理http.Dir的notFound?

这是我的目录结构 enter image description here

1 个答案:

答案 0 :(得分:1)

来自uiAppHandler的回复为空,因为该函数未写入回复w。您应该直接使用mux注册文件服务器处理程序,而不是尝试创建处理程序:

r.PathPrefix("/app").Handler(http.StripPrefix("/app/", http.FileServer(http.Dir(repoFrontend1))))

mux将带有前缀“/ app”的所有请求传递给为该前缀注册的处理程序。具有该前缀的所有请求都可以在多路复用器方面找到。 http.FileServer或您为该前缀注册的任何内容都负责生成404响应。