goip

package module
v0.0.0-...-63aa332 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 7, 2024 License: MIT Imports: 7 Imported by: 0

README

goip

GoDoc Go Report Card

A golang library that get client ip from HTTP request

The gin web framework is a very good framework, with its own integration of the ClientIP() method, but there will be cases in the actual project without the gin framework, just to use the ClientIP() method code would be too heavy, so stand on the shoulders of the giants, pull out the relevant code, and do some extensions.

Features

  • X-Real-IP rules are supported
  • Follows the rule of X-Forwarded-For
  • Follows the rule of RFC-7239 standard Forwarded
  • The trusted local or private address is allowed to be configured
  • Allows getting ip from custom headers

Installation

required golang version 1.21+

go get github.com/chaunsin/goip

Example

package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"

	"github.com/chaunsin/goip"
)

func Example() {
	var serverAddress = "127.0.0.1:8080"

	myParse, err := goip.NewParse([]string{"127.0.0.1"})
	if err != nil {
		log.Println(err)
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// Set the global trusted proxy addresses,
		// If not set, the default priority is used
		if err := goip.SetTrustedProxies([]string{"127.0.0.1"}); err != nil {
			log.Println(err)
		}

		// Use the global default configuration
		ip := goip.ClientIP(r)
		// Use custom configuration
		_ = myParse.ClientIP(r)

		// Get the ip address from X-Appengine-Remote-Addr first.
		// If the IP address cannot be obtained, try to get it from another lower priority
		_ = goip.ClientIP(r, goip.XAppEngineRemoteAddr)
		_ = myParse.ClientIP(r, goip.XAppEngineRemoteAddr)

		// Use the custom configuration
		_ = goip.ClientIP(r, goip.XHeader("X-My-IP"))
		_ = myParse.ClientIP(r)

		fmt.Fprintf(w, "Your IP address is %s", ip)
	})
	go func() {
		log.Println(http.ListenAndServe(serverAddress, nil))
	}()

	// execute http request
	req, err := http.NewRequest("GET", "http://"+serverAddress, nil)
	if err != nil {
		panic(err)
	}
	// simulated proxy server added address information
	req.Header.Set("X-Forwarded-For", "123.123.0,1, 123.123.0.2")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	io.Copy(os.Stdout, resp.Body)

	// Output:
	// Your IP address is 123.123.0.2
}

How does it work?

The basic principle is to look up the specified object value from the HTTP request header.

The following process is used to search for an ip address:

  1. If the user a custom request header( e.g. CF-Connecting-IP 、X-Appengine-Remote-Addr...), the fetch is attempted directly from the request header.
  2. Get RemoteAddr to determine whether the address is in the trusted whitelist, and if so, go to Step 3,Otherwise, go to Step 4 return RemoteAddr
  3. If RemoteAddr is a trusted address, it attempts to get an ip address from X-Real-IP、X-Forward-For、Forwarded, and reverse-searches for the first ip address that is not in the trusted address list
  4. return ip

Thanks

Documentation

Overview

Example
var serverAddress = "127.0.0.1:8080"

myParse, err := NewParse([]string{"127.0.0.1"})
if err != nil {
	log.Println(err)
}

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
	// Set the global trusted proxy addresses,
	// If not set, the default priority is used
	if err := SetTrustedProxies([]string{"127.0.0.1"}); err != nil {
		log.Println(err)
	}

	// Use the global default configuration
	ip := ClientIP(r)
	// Use custom configuration
	_ = myParse.ClientIP(r)

	// Get the ip address from X-Appengine-Remote-Addr first.
	// If the IP address cannot be obtained, try to get it from another lower priority
	_ = ClientIP(r, XAppEngineRemoteAddr)
	_ = myParse.ClientIP(r, XAppEngineRemoteAddr)

	// Use the custom configuration
	_ = ClientIP(r, XHeader("X-My-IP"))
	_ = myParse.ClientIP(r)

	fmt.Fprintf(w, "Your IP address is %s", ip)
})
go func() {
	log.Println(http.ListenAndServe(serverAddress, nil))
}()

// execute http request
req, err := http.NewRequest("GET", "http://"+serverAddress, nil)
if err != nil {
	panic(err)
}
// simulated proxy server added address information
req.Header.Set("X-Forwarded-For", "123.123.0,1, 123.123.0.2")
resp, err := http.DefaultClient.Do(req)
if err != nil {
	panic(err)
}
defer resp.Body.Close()
io.Copy(os.Stdout, resp.Body)
Output:

Your IP address is 123.123.0.2

Index

Examples

Constants

View Source
const Forwarded = "Forwarded"

Forwarded standard RFC-7239 https://www.rfc-editor.org/rfc/rfc7239.txt

Variables

This section is empty.

Functions

func ClientIP

func ClientIP(req *http.Request, customHeader ...XHeader) string

ClientIP get the ip address from the global default configuration

func SetTrustedProxies

func SetTrustedProxies(proxies []string) error

SetTrustedProxies Set a global trusted proxy server address

Types

type ForwardedHeader

type ForwardedHeader struct {
	For   string
	By    string
	Host  string
	Proto string
}

ForwardedHeader represents the structure of a parsed Forwarded header standard RFC-7239 https://www.rfc-editor.org/rfc/rfc7239.txt section 5

func ParseForwardedHeader

func ParseForwardedHeader(headerValue string) ([]ForwardedHeader, error)

ParseForwardedHeader parses the Forwarded header value and returns a slice of ForwardedHeader e.g. - Forwarded: for=192.0.2.43, for=198.51.100.17;by=203.0.113.60;proto=http;host=example.com - Forwarded: for="[2001:db8:cafe::17]", for=unknown

type Parser

type Parser struct {
	// contains filtered or unexported fields
}

func NewParse

func NewParse(proxies []string, customHeader ...XHeader) (*Parser, error)

func (*Parser) ClientIP

func (p *Parser) ClientIP(req *http.Request, customHeader ...XHeader) string

ClientIP get client ip. like ClientIP()

func (*Parser) SetTrustedProxies

func (p *Parser) SetTrustedProxies(proxies []string) (err error)

SetTrustedProxies Set a trusted proxy server address. like SetTrustedProxies()

type XHeader

type XHeader string
const (
	// XForwardedFor X-Forwarded-For
	XForwardedFor XHeader = "X-Forwarded-For"
	// XRealIP commonly used for Nginx、Apache HTTP Server, etc.
	XRealIP XHeader = "X-Real-IP"
	// XClientIP used by Amazon EC2, Heroku, and others
	XClientIP XHeader = "X-Client-IP"
	// CFConnectingIP used by Cloudflare.
	// - https://developers.cloudflare.com/fundamentals/reference/http-request-headers/#cf-connecting-ip
	CFConnectingIP XHeader = "CF-Connecting-IP"
	// FastlyClientIp Fastly CDN and Firebase hosting header when forward to a cloud function
	FastlyClientIp XHeader = "Fastly-Client-Ip"
	// TrueClientIp Akamai and Cloudflare(enterprise plan only)
	TrueClientIp XHeader = "True-Client-Ip"
	// XAppEngineRemoteAddr Google App Engine(GAE)
	XAppEngineRemoteAddr XHeader = "X-Appengine-Remote-Addr"
	// FlyClientIP when running on Fly.io
	FlyClientIP XHeader = "Fly-Client-IP"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL