Skip to content

A middleware for determining client IP addresses of proxied requests for Golang.

License

Notifications You must be signed in to change notification settings

zesik/proxyaddr

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

proxyaddr

GoDoc Build Status Coverage Status Go Report Card

Package proxyaddr is a middleware for determining client address for proxied requests in Go.

After proxyaddr is set with trusted proxies (such as local nginx, HAProxy, etc.), it tries to get the actual IP address of clients from x-forwarded-for HTTP header. If presents, proxyaddr sets the IP address to RemoteAddr field of the http.Request instance. Note the port number in RemoteAddr is left unchanged.

Install

go get github.com/zesik/proxyaddr

Quick Example

Using with standard net/http:

package main

import (
	"net/http"

	"github.com/zesik/proxyaddr"
)

func main() {
	pa := &proxyaddr.ProxyAddr{}
	pa.Init(proxyaddr.CIDRLoopback)
	http.ListenAndServe(":8080", pa.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(r.RemoteAddr))
	})))
}

Using with Negroni:

package main

import (
	"net/http"

	"github.com/urfave/negroni"
	"github.com/zesik/proxyaddr"
)

func main() {
	pa := &proxyaddr.ProxyAddr{}
	pa.Init(proxyaddr.CIDRLoopback)

	n := negroni.New()
	n.Use(pa)
	n.UseHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(r.RemoteAddr))
	}))

	http.ListenAndServe(":8080", n)
}

A quick test with curl:

$ curl localhost:8080
[::1]:53998

$ curl -H "x-forwarded-for: 1.2.3.4, 5.6.7.8" localhost:8080
5.6.7.8:53999

License

MIT

About

A middleware for determining client IP addresses of proxied requests for Golang.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages