⚠️ Status: untested. This extension is provided as-is and has not been tested in production. Please feel free to fork, modify, improve, and open pull requests.Licensed under GNU GPLv3 (see LICENSE).
Standard net/http middleware — func(http.Handler) http.Handler — that checks
each request against the ip-block.com service and
blocks disallowed clients.
Targets: Go 1.20+, stdlib net/http (works with chi, gorilla/mux, and any
router that accepts standard middleware).
go get github.com/ip-block/ipblock-gopackage main
import (
"net/http"
"time"
ipblock "github.com/ip-block/ipblock-go"
)
func main() {
cfg := ipblock.Default()
cfg.SiteID = "your-site-id"
cfg.APIKey = "your-api-key"
cfg.BehindProxy = true
cfg.Whitelist = []string{"127.0.0.1", "10.0.0.0/8"}
middleware := ipblock.New(cfg)
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("Hello"))
})
http.ListenAndServe(":8080", middleware(mux))
}Wrapping a single handler works the same way: middleware(myHandler).
| Field | Default |
|---|---|
Enabled |
true |
SiteID |
"" |
APIKey |
"" |
APIURL |
https://api.ip-block.com/v1/check |
FailOpen |
true (allow on error/timeout) |
CacheTTL |
300 * time.Second |
Timeout |
1 * time.Second |
BehindProxy |
false |
BlockAction |
"403" (or "redirect") |
RedirectURL |
https://www.ip-block.com/blocked.php |
BlockMessage |
"Access denied." |
Whitelist |
nil (IPs and CIDR ranges) |
Logger |
nil (optional *log.Logger) |
- Builds
{api_key, site_id, ip, user_agent, referrer}andPOSTs it with anhttp.ClientwhoseTimeoutis 1 second. - Blocks only when the response is
{"action":"block"}. - Fails open on any error/timeout/non-2xx/missing
action(cfg.FailOpen = falseto fail closed). - Caches each decision for
CacheTTLin a mutex-guarded map, keyed bymd5(ip|user_agent|referrer). - Honours
Whitelist(individual IPs and CIDR ranges vianet). - Reads the real client IP from
RemoteAddr; withBehindProxy = trueit trustsCF-Connecting-IPthen the firstX-Forwarded-Forhop.