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

3 篇文章 0 订阅

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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值