Golang net/http和Gorilla:在处理程序之前运行代码 [英] Golang net/http and Gorilla: run code before handler

查看:49
本文介绍了Golang net/http和Gorilla:在处理程序之前运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在进入处理程序之前,是否可以使用net/http包和/或任何大猩猩库在每个URL上执行一些代码?例如,要检查连接是否来自列入黑名单的IP地址?

Is it possible using the net/http package and/or any of the gorilla libraries to make some code execute on EVERY URL before going to the handler? For example, to check if a connection is coming from a black listed IP address?

推荐答案

创建一个在检查IP地址后调用另一个处理程序的处理程序:

Create a handler that invokes another handler after checking the IP address:

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)
}

将此处理程序而不是原始处理程序传递给ListenAndServe.例如,如果您有:

Pass this handler to ListenAndServe instead of your original handler. For example, if you had:

err := http.ListenAndServe(addr, mux)

将代码更改为

err := http.ListenAndServe(addr, checker{mux})

这也适用于ListenAndServe的所有变体.它可以与http.ServeMux,Gorilla mux和其他路由器配合使用.

This also applies to all the variations of ListenAndServe. It works with http.ServeMux, Gorilla mux and other routers.

这篇关于Golang net/http和Gorilla:在处理程序之前运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆