ipfilterware

package module
v0.2.0 Latest Latest
Warning

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

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

README

ipfilterware

build-img pkg-img reportcard-img coverage-img

Go HTTP middleware to filter clients by IP address.

Rationale

To protect your application open to the internet you might want to allow only verified or well-known IPs. This can be easily done via firewall but sometimes you do not have access to such tools (cloud providers, proxies, serverless, etc). To make this real you can check a connection IP and check it with your config. This library does this.

Features

  • Simple API.
  • Clean and tested code.
  • Thread-safe updates.
  • Dependency-free.
  • Fetches for popular providers.

Install

Go version 1.17+

go get github.com/cristalhq/ipfilterware

Example

// your handler or mux/router
var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	// do something good
	w.WriteHeader(http.StatusOK)
})

// some IPs to allow (see fetchers_test.go for DNS and proxy helpers)
ips := []string{"10.20.30.40", "100.100.99.1", "42.42.42.42"}

// create ipfilterware handler to pass allowed IPs to myHandler 
handler, err := ipfilterware.New(myHandler, &ipfilterware.Config{
	AllowedIPs: ips,
})
if err != nil {
	panic(err)
}

// use handler as a router or middleware
http.ListenAndServe(":8080", handler)

Documentation

See these docs.

License

MIT License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// AllowedIPs list of IPs and/or CIDRs.
	AllowedIPs []string

	// ForbiddenHandler will be invoked when client is blocked.
	// If nil then http.Error will be used.
	ForbiddenHandler http.Handler
}

Config for the handler.

type Handler

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

Handler to filter client by IP.

func New

func New(next http.Handler, cfg *Config) (*Handler, error)

New creates a new handler which wraps handler given based on a config.

func (*Handler) IsAllowed

func (h *Handler) IsAllowed(ip netip.Addr) bool

IsAllowed reports whether given IP is allowed.

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler interface.

func (*Handler) Update

func (h *Handler) Update(cfg *Config) error

Update the handler with a config in a concurrent safe way.

func (*Handler) Wrap

func (h *Handler) Wrap(next http.Handler) http.Handler

Wrap a given handler.

Jump to

Keyboard shortcuts

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