排除正则表达式中的favicon图标。

huangapple go评论65阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2021年6月20日 01:14:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/68049145.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定