foxgeoip

package module
v0.22.0 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2025 License: MIT Imports: 7 Imported by: 0

README

Go Reference tests Go Report Card codecov GitHub release (latest SemVer) GitHub go.mod Go version

Foxgeoip

FoxGeoIP is an experimental middleware for Fox that filters incoming requests based on the client's IP address using GeoIP data. It blocks or allows access based on country codes. This middleware is intended to work with MaxMind GeoLite2 or GeoIP2 databases. It may work with other geolocation databases as well.

Disclaimer

FoxGeoIP's API is closely tied to the Fox router, and it will only reach v1 when the router is stabilized. During the pre-v1 phase, breaking changes may occur and will be documented in the release notes.

Getting started

Installation
go get -u github.com/tigerwill90/foxgeoip
Feature
  • Filters requests based on country codes, either allowing or blocking them.
  • Supports whitelists or blacklists mode.
  • Tightly integrates with the Fox ecosystem for enhanced performance and scalability.
  • Provides structured logging with log/slog.
Usage
package main

import (
	"errors"
	"github.com/oschwald/geoip2-golang"
	"github.com/tigerwill90/fox"
	"github.com/tigerwill90/fox/clientip"
	"github.com/tigerwill90/foxgeoip"
	"log"
	"net/http"
)

func main() {
	db, err := geoip2.Open("GeoLite2-Country.mmdb")
	if err != nil {
		panic(err)
	}
	defer db.Close()

	resolver, err := clientip.NewRightmostNonPrivate(clientip.XForwardedForKey)
	if err != nil {
		panic(err)
	}
	f, err := fox.New(
		fox.DefaultOptions(),
		fox.WithClientIPResolver(resolver),
		fox.WithMiddleware(
			foxgeoip.Middleware(
				db,
				foxgeoip.WithBlacklistedCountries("US", "CN", "AU"),
			),
		),
	)
	if err != nil {
		panic(err)
	}

	f.MustHandle(http.MethodGet, "/hello/{name}", func(c fox.Context) {
		_ = c.String(http.StatusOK, "hello %s\n", c.Param("name"))
	})

	if err = http.ListenAndServe(":8080", f); err != nil && !errors.Is(err, http.ErrServerClosed) {
		log.Fatalln(err)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultBlockingResponse

func DefaultBlockingResponse(c fox.Context)

DefaultBlockingResponse is the default response for blocked IPs. It responds with a 403 Forbidden http status.

func Middleware

func Middleware(db *geoip2.Reader, opts ...Option) fox.MiddlewareFunc

Middleware creates a middleware function for the IP filter. The middleware is intended to work with MaxMind GeoLite2 or GeoIP2 databases. It should work with other MMDB databases but has not been tested. Note that blacklist and whitelist options are mutually exclusive. Either it is a whitelist, and all requests are denied except for IPs that have a country code associated in the whitelist, OR it is a blacklist, and all requests are allowed except IPs that have a country code associated in the blacklist.

Types

type Filter

type Filter func(c fox.Context) bool

type IPFilter

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

func New

func New(db *geoip2.Reader, opts ...Option) *IPFilter

New creates a new IPFilter with the provided GeoIP2 reader and options. The ip filter is intended to work with MaxMind GeoLite2 or GeoIP2 databases. It should work with other MMDB databases but has not been tested. Note that blacklist and whitelist options are mutually exclusive. Either it is a whitelist, and all requests are denied except for IPs that have a country code associated in the whitelist, OR it is a blacklist, and all requests are allowed except IPs that have a country code associated in the blacklist.

func (*IPFilter) Allowed

func (f *IPFilter) Allowed(ip net.IP) (allowed bool, code string, err error)

Allowed checks if the given IP address is allowed based on the filter's configuration.

func (*IPFilter) FilterIP

func (f *IPFilter) FilterIP(next fox.HandlerFunc) fox.HandlerFunc

FilterIP is a middleware function that filters requests based on the IP address.

type Option

type Option interface {
	// contains filtered or unexported methods
}

func WithBlacklistedCountries

func WithBlacklistedCountries(codes ...string) Option

WithBlacklistedCountries sets the blacklist with the provided country codes. It clears any existing whitelist. Requests from countries in the blacklist will be denied.

func WithClientIPResolver added in v0.19.0

func WithClientIPResolver(resolver fox.ClientIPResolver) Option

WithClientIPResolver sets a custom resolver to determine the client IP address. This is for advanced use case, you should configure the resolver with Fox's router option using fox.WithClientIPResolver.

func WithFilter

func WithFilter(f ...Filter) Option

WithFilter appends the provided filters to the middleware's filter list. A filter returning true will exclude the request from using the ip filter handler. If no filters are provided, all requests will be handled. Keep in mind that filters are invoked for each request, so they should be simple and efficient.

func WithLogHandler

func WithLogHandler(handler slog.Handler) Option

WithLogHandler sets a custom log handler for structured logging.

func WithResponse

func WithResponse(handler fox.HandlerFunc) Option

WithResponse sets a custom response handler for blocked requests.

func WithWhitelistedCountries

func WithWhitelistedCountries(codes ...string) Option

WithWhitelistedCountries sets the whitelist with the provided country codes. It clears any existing blacklist. Requests from countries not in the whitelist will be denied.

Jump to

Keyboard shortcuts

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