This package provides an in-memory IP filtering system. It allows for dynamic IP filtering based on a set of rules that can be easily managed and updated.
- Allow or deny specific IP addresses or CIDR ranges
- Automatic filtering of private and special IP ranges
- In-memory rule storage for fast access
- JSON serialization and deserialization of rules
The IP filter works by maintaining a list of rules in memory. Each rule consists of:
- Action: "allow" or "deny"
- Target: An IP address, CIDR range, or "all" (which applies to all IPs)
When an IP address is checked against the filter:
- If there are no rules, all IPs are allowed.
- If the IP is a private or special address (e.g., loopback, multicast), it's automatically denied.
- Rules are checked in order.
- The first rule that matches the IP determines whether the IP is allowed or denied.
- If the IP matches a rule, no other rules are checked.
- If the IP does not match any rule, the IP is denied by default.
The package provides methods to:
- Add rules (append or at a specific position)
- Remove rules
- Get all rules or a specific rule
- Count rules
- Remove all rules
Rules are stored in memory as a slice, allowing for efficient management and retrieval.
To use this package in your Go project:
-
Import the package:
import "github.com/mike-plivo/ipfilter"
-
Create a new IPFilter instance:
jsonRules := `[{"action":"allow","target":"203.0.113.0/24"}]` filter, err := ipfilter.NewIPFilter(jsonRules) if err != nil { // Handle error }
-
Check if an IP is allowed:
allowed, err := filter.IsAllowedIP("203.0.113.100") if err != nil { // Handle error } if allowed { // Allow the connection } else { // Deny the connection }
-
Add a new rule:
rule := ipfilter.Rule{Action: "allow", Target: "192.0.2.0/24"} err := filter.AppendRule(rule) if err != nil { // Handle error }
-
Convert rules to JSON:
jsonRules, err := filter.ToJSON() if err != nil { // Handle error }
- Go 1.13 or later
-
Install Go 1.13 or later (if not already installed)
-
Clone the repository:
git clone https://github.com/mike-plivo/ipfilter.git cd ipfilter -
Install dependencies:
go mod download
To run tests for this package, you can use the standard Go testing tools:
go test .
To run benchmarks for this package, you can use the standard Go benchmarking tools:
go test -bench=. .
You can use Docker to build, test, and benchmark this package. Here's how:
-
Build the Docker image:
docker build -t ipfilter . -
Run tests:
docker run --rm ipfilter test -
Run benchmarks:
docker run --rm ipfilter benchmark -
Run examples:
docker run --rm ipfilter examples -
Start a shell in the container:
docker run --rm -it ipfilter shell
These commands utilize the start.sh script in the container to execute different actions based on the provided argument.
Contributions are welcome! Please feel free to submit a Pull Request.
MIT