realip

package module
v0.0.0-...-b44d216 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2017 License: MIT Imports: 5 Imported by: 2

README

GoMiddleware : IP

Middleware that sets a RealIP in your request's context (r.Context()).

Synopsis

package main

import (
	"net/http"

	"github.com/gomiddleware/realip"
)

func handler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte(r.URL.Path))
}

func main() {
    handle := realip(http.HandlerFunc(handler))
	http.Handle("/", handle)
	http.ListenAndServe(":8080", nil)
}

Author

By Andrew Chilton, @twitter.

For AppsAttic, @AppsAttic.

License

MIT.

(Ends)

Documentation

Overview

Package realip provides standard http.Handler middleware that sets a value in the Request's context to the result of parsing either the X-Forwarded-For header or the X-Real-IP header (in that order).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RealIp

func RealIp(next http.Handler) http.Handler

RealIp is middleware that parses either the X-Forwarded-For header or the X-Real-IP header (in that order). It stores the result in the request's context for later retrieval during the request lifecycle.

If neither of these are available, we check the req.RemoteAddr for the original value. This may or may not contain what you really want, but it is the best guess we have.

If none of these provide an IP address, we just store the empty string instead of an IP address.

This middleware should be inserted fairly early in the middleware stack to ensure that subsequent layers (eg., request loggers) which require the RealIp will see the intended value. Other GoMiddleware, such as gomiddleware/logger can use this information.

You should only use this middleware if you can trust the headers passed to you (in particular, the two headers this middleware uses). If you have placed a reverse proxy like HAProxy or Nginx in front of your server and forwarded the correct headers then you should be fine. However, if your reverse proxy is configured to pass along arbitrary header values from the client, or if you use this middleware without a reverse proxy, malicious clients will be able to inject values that are not correct and may even cause a vulnerability if used incorrectly.

func RealIpFromContext

func RealIpFromContext(ctx context.Context) string

RealIpFromContext can be used to obtain the RealIp from the context (if you already have it handy).

func RealIpFromRequest

func RealIpFromRequest(r *http.Request) string

RealIpFromRequest can be used to obtain the RealIp from the request. This is given as a convenience method for RealIpFromContext if you don't have the context handy, but you do (of course) have the http.Request.

Types

This section is empty.

Jump to

Keyboard shortcuts

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