英文:
Exclude favicon in regex
问题
我有一个使用状态在URL中的网站,例如:
/alabama
/alaska
但是网站的favicon使用了相同的路径:
/favicon.ico
这是路由的设置:
router.HandleFunc("/{[a-z]+\b*[favicon.ico]\b}", stateHandler).Methods("GET")
favicon没有被排除在模式之外。
有什么想法吗?
英文:
I have a site that uses states in the url, like
/alabama
/alaska
But the favicon is using the same path.
/favicon.ico
This is the route:
router.HandleFunc("/{[a-z]+\b*[favicon.ico]\b}", stateHandler).Methods("GET")
The favicon is not being excluded from the pattern.
Any ideas?
答案1
得分: 1
根据Peter
的说法,你可以为/favicon.ico
路由注册http.NotFoundHandler
。
router.HandleFunc("/favicon.ico", http.NotFoundHandler).Methods("GET")
你也可以编写中间件。
// 中间件函数,将在每个请求中调用
func FaviconMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if (!strings.Contains(r.URL.Path, "favicon.ico")) {
http.NotFoundHandler()
}
else {
next.ServeHTTP(w, r)
}
})
}
r.Use(FaviconMiddleware)
英文:
As stated by Peter
that you can register http.NotFoundHandler for /favicon.ico
route
router.HandleFunc("/favicon.ico", http.NotFoundHandler).Methods("GET")
You can also write middleware
// Middleware function, which will be called for each request
func FaviconMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if (!strings.Contains(r.URL.Path, "favicon.ico")) {
http.NotFoundHandler()
}
else {
next.ServeHTTP(w, r)
}
})
}
r.Use(FaviconMiddleware)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论