Go语言:用goutils包获取HTTP请求客户端IP,支持优先从代理转发的请求头读取IP

goutils包的GetClientIP()函数封装了优先从代理转发的请求头读取IP,若找不到则读取http.Request.RemoteAddr的功能。

源码:

// GetClientIP return the client IP of a http request, by the order
// of a given list of headers. If no ip is found in headers, then return request's
// RemoteAddr. This is useful when there are proxy servers between the client and the backend server.
// Example:
// GetClientIP(r,"x-real-ip","x-forwarded-for"), will first check header "x-real-ip"
// if it exists, then split it by "," and return the first part. Otherwise, it will check
// the header "x-forwarded-for" if it exists, then split it by "," and return the first part.
// Otherwise it will return request's RemoteAddr.
//
func GetClientIP(r *http.Request, headers ...string) string {
	for _, header := range headers {
		ip := r.Header.Get(header)
		if ip != "" {
			return strings.Split(ip, ",")[0]
		}
	}
	return strings.Split(r.RemoteAddr, ":")[0]
}

使用方法:

package main

import(
	"fmt"
	"github.com/pochard/goutils"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request){
	clientIp := goutils.GetClientIP(r,"x-real-ip","x-forwarded-for")
	fmt.Printf("client ip = %s\n", clientIp)
	fmt.Fprintf(w, "Hello")
}

func main(){
	http.HandleFunc("/", handler)
	http.ListenAndServe(":8080", nil)
}

当请求包含如下请求头时:

则输出

client ip = 10.1.5.89
发布了53 篇原创文章 · 获赞 3 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/pengpengzhou/article/details/105294853