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.
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.
go get -u github.com/tigerwill90/foxgeoip
- 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
.
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)
}
}