Skip to content

IP-Block-Ltd/ipblock-go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

⚠️ 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).

IP Block — Go (net/http) Middleware

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).

Install

go get github.com/ip-block/ipblock-go

Register

package 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).

Config (defaults from ipblock.Default())

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)

How it works

  • Builds {api_key, site_id, ip, user_agent, referrer} and POSTs it with an http.Client whose Timeout is 1 second.
  • Blocks only when the response is {"action":"block"}.
  • Fails open on any error/timeout/non-2xx/missing action (cfg.FailOpen = false to fail closed).
  • Caches each decision for CacheTTL in a mutex-guarded map, keyed by md5(ip|user_agent|referrer).
  • Honours Whitelist (individual IPs and CIDR ranges via net).
  • Reads the real client IP from RemoteAddr; with BehindProxy = true it trusts CF-Connecting-IP then the first X-Forwarded-For hop.

About

IP Block protection for Go (net/http) — ip-block.com integration. Untested at the moment; please feel free to modify. GPLv3.

Topics

Resources

License

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages