英文:
"Blank response" NotFoundHandler not working Gorilla
问题
我正在尝试通过编写自定义的未找到处理程序来调试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() {
// 创建一个MUX
r := mux.NewRouter()
http.Handle("/", r)
r.NotFoundHandler = http.HandlerFunc(NotFound)
// 静态文件
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))).ServeHTTP(w, r)
}
我对现有文件和不存在的文件都得到了空白响应。我猜测由于我的"/"处理程序,NotFound没有被触发。那么我该如何处理http.Dir的NotFound呢?
这是我的目录结构:
英文:
I am trying to debug 404-not-found by writing a custom not-found handler. Here is my code.
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)))
}
I am getting a blank response for both existing and non-existing files. I guess NotFound is not getting triggered because of my "/" handler. Then how do I handle notFound for http.Dir?
Here is my directory structure
答案1
得分: 1
uiAppHandler
的响应为空,因为该函数没有向响应w
写入内容。你应该直接将文件服务器处理程序与mux注册,而不是尝试创建一个处理程序:
r.PathPrefix("/app").Handler(http.StripPrefix("/app/", http.FileServer(http.Dir(repoFrontend1))))
mux将所有以"/app"前缀开头的请求传递给为该前缀注册的处理程序。就mux而言,所有具有该前缀的请求都会被找到。http.FileServer或者你为该前缀注册的任何处理程序都负责生成404响应。
英文:
The response from uiAppHandler
is blank because the function does not write to the response w
. You should register the file server handler directly with the mux instead of trying to create a handler:
r.PathPrefix("/app").Handler(http.StripPrefix("/app/", http.FileServer(http.Dir(repoFrontend1))))
The mux passes all requests with the prefix "/app" to the handler registered for that prefix. All requests with that prefix are found as far as the mux is concerned. The http.FileServer or whatever you register for that prefix is responsible for generating the 404 response.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论