是否可以使用net/http包和/或任何gorilla库在转到处理程序之前在EVERY URL上执行某些代码?例如,要检查连接是否来自黑名单的IP地址?
创建一个在检查IP地址后调用另一个处理程序的处理程序:
type checker struct {
h http.Handler
}
func (c checker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if blackListed(r.RemoteAddr) {
http.Error(w, "not authorized", http.StatusForbidden)
return
}
c.h.ServeHTTP(w, r)
}
Run Code Online (Sandbox Code Playgroud)
将此处理程序传递给ListenAndServe而不是原始处理程序.例如,如果你有:
err := http.ListenAndServe(addr, mux)
Run Code Online (Sandbox Code Playgroud)
将代码更改为
err := http.ListenAndServe(addr, checker{mux})
Run Code Online (Sandbox Code Playgroud)
这也适用于ListenAndServe的所有变体.它适用于http.ServeMux,Gorilla mux和其他路由器.
| 归档时间: |
|
| 查看次数: |
903 次 |
| 最近记录: |