gpt4 book ai didi

http - 使用golang http包时如何限制客户端IP地址

转载 作者:IT王子 更新时间:2023-10-29 00:53:46 26 4
gpt4 key购买 nike

我正在使用 golang http 包。服务器如何限制客户端IP地址?

func (s *Worker) Run(c chan error) {
apiMux := http.NewServeMux()
apiMux.HandleFunc("/test", s.test)
apiMux.HandleFunc("/block/create", s.CreateBlock)
apiMux.HandleFunc("/block/delete", s.DeleteBlock)

apiServer := &http.Server{
Addr: "0.0.0.0:" + strconv.Itoa(s.ListenPort),
Handler: apiMux,
}

go func() {
log.Println("Worker listening on " + apiServer.Addr)
c <- apiServer.ListenAndServe()
}()
}

最佳答案

您需要做两件事:一是用中间件处理程序包装您的多路复用器,该处理程序会预处理您的请求并验证 IP。另一个是获取用户的真实 IP,如果您在防火墙或负载均衡器后面(导致地址始终是 LB 的地址),或者如果您的用户在代理后面,这很重要。

至于包装你的多路复用器,它非常简单:

apiServer := &http.Server{
Addr: "0.0.0.0:8080",
Handler: http.HandlerFunc( func(w http.ResponseWriter, req *http.Request) {
// get the real IP of the user, see below
addr := getRealAddr(req)

// the actual vaildation - replace with whatever you want
if (addr != "1.2.3.4") {
http.Error(w, "Blocked", 401)
return
}
// pass the request to the mux
apiMux.ServeHTTP(w,req)
}),
}

我附加了 getRealAddr 函数,它来自一个实际项目,我在其中做了类似这样的事情:

func getRealAddr(r *http.Request)  string {

remoteIP := ""
// the default is the originating ip. but we try to find better options because this is almost
// never the right IP
if parts := strings.Split(r.RemoteAddr, ":"); len(parts) == 2 {
remoteIP = parts[0]
}
// If we have a forwarded-for header, take the address from there
if xff := strings.Trim(r.Header.Get("X-Forwarded-For"), ","); len(xff) > 0 {
addrs := strings.Split(xff, ",")
lastFwd := addrs[len(addrs)-1]
if ip := net.ParseIP(lastFwd); ip != nil {
remoteIP = ip.String()
}
// parse X-Real-Ip header
} else if xri := r.Header.Get("X-Real-Ip"); len(xri) > 0 {
if ip := net.ParseIP(xri); ip != nil {
remoteIP = ip.String()
}
}

return remoteIP

}

至于过滤,它可以基于一组 ips 或 CIDR 范围,当然由您决定。

如果您有兴趣,上面的代码来 self 编写和使用的 API 构建工具包,称为 Vertex,它内置了这个:https://github.com/EverythingMe/vertex

关于http - 使用golang http包时如何限制客户端IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37896931/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com