This is part 3 of a series on GoWind, the framework behind our 20+ product suite:
- The building-block architecture — a core under 500 lines, 130+ plugins
- One YAML file is your architecture — assembling HTTP/gRPC/DB/cache/tracing from config alone
A framework with a tiny core makes a bold implicit promise: you should be able to extend it without touching it. Today we're going to cash that promise in, by building a real, working middleware plugin from scratch — an IP blocklist supporting exact IPs and CIDR ranges, configured entirely from YAML, registered via the framework's SPI, and wired in with a single blank import.
By the end you'll also have seen the three Go idioms the whole plugin system is built on: functional options, init()-based self-registration, and config-driven assembly.
What we're building
A middleware that:
- reads blocked IPs and CIDR ranges from YAML
- rejects requests with a configurable status code and message
- skips health-check style paths
- extracts the client IP correctly from
X-Forwarded-For/X-Real-IP/RemoteAddr
Step 1: Options — the With* family
// plugins/middleware/ip_blocklist/option.go
package ip_blocklist
type Option func(*Config)
type Config struct {
IPList []string `yaml:"ip_list"`
CIDRList []string `yaml:"cidr_list"`
StatusCode int `yaml:"status_code"`
Message string `yaml:"message"`
SkipPaths []string `yaml:"skip_paths"`
}
func WithIPList(ips []string) Option { return func(c *Config) { c.IPList = ips } }
func WithCIDRList(cidrs []string) Option { return func(c *Config) { c.CIDRList = cidrs } }
func WithStatusCode(code int) Option { return func(c *Config) { c.StatusCode = code } }
func WithMessage(msg string) Option { return func(c *Config) { c.Message = msg } }
func WithSkipPaths(paths []string) Option { return func(c *Config) { c.SkipPaths = paths } }
Functional options keep the constructor stable as the config grows — the same pattern GoWind's own 130+ plugins use.
Step 2: The middleware itself
// plugins/middleware/ip_blocklist/middleware.go
package ip_blocklist
import (
"net"
"net/http"
"strings"
)
type Middleware struct {
config *Config
ipSet map[string]bool
cidrNetworks []*net.IPNet
}
func New(opts ...Option) *Middleware {
cfg := &Config{
StatusCode: http.StatusForbidden,
Message: "Access denied",
}
for _, opt := range opts {
opt(cfg)
}
m := &Middleware{config: cfg}
m.ipSet = make(map[string]bool, len(cfg.IPList))
for _, ip := range cfg.IPList {
m.ipSet[strings.TrimSpace(ip)] = true
}
for _, cidr := range cfg.CIDRList {
if _, network, err := net.ParseCIDR(cidr); err == nil {
m.cidrNetworks = append(m.cidrNetworks, network)
}
}
return m
}
func (m *Middleware) Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for _, path := range m.config.SkipPaths {
if r.URL.Path == path {
next.ServeHTTP(w, r)
return
}
}
clientIP := extractIP(r)
if m.ipSet[clientIP] {
w.WriteHeader(m.config.StatusCode)
_, _ = w.Write([]byte(m.config.Message))
return
}
ip := net.ParseIP(clientIP)
for _, network := range m.cidrNetworks {
if network.Contains(ip) {
w.WriteHeader(m.config.StatusCode)
_, _ = w.Write([]byte(m.config.Message))
return
}
}
next.ServeHTTP(w, r)
})
}
func extractIP(r *http.Request) string {
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
if idx := strings.Index(xff, ","); idx > 0 {
return strings.TrimSpace(xff[:idx])
}
return strings.TrimSpace(xff)
}
if xri := r.Header.Get("X-Real-IP"); xri != "" {
return xri
}
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return host
}
Note the design choice: CIDRs are parsed once in New, not per request. Middlewares sit on the hot path; do your allocations at construction time.
Step 3: Register with the SPI
This is where the plugin becomes part of the framework. Inside init(), we register a factory that maps the raw YAML block to our options:
// plugins/middleware/ip_blocklist/register.go
package ip_blocklist
import (
"net/http"
"github.com/tx7do/go-wind-bootstrap/middleware"
)
func init() {
middleware.RegisterWithConfig("ip_blocklist", func(raw map[string]interface{}) func(http.Handler) http.Handler {
cfg := &Config{
StatusCode: http.StatusForbidden,
Message: "Access denied",
}
if v, ok := raw["ip_list"]; ok {
for _, ip := range v.([]interface{}) {
cfg.IPList = append(cfg.IPList, ip.(string))
}
}
if v, ok := raw["cidr_list"]; ok {
for _, cidr := range v.([]interface{}) {
cfg.CIDRList = append(cfg.CIDRList, cidr.(string))
}
}
if v, ok := raw["status_code"]; ok {
cfg.StatusCode = int(v.(int))
}
if v, ok := raw["message"]; ok {
cfg.Message = v.(string)
}
if v, ok := raw["skip_paths"]; ok {
for _, p := range v.([]interface{}) {
cfg.SkipPaths = append(cfg.SkipPaths, p.(string))
}
}
m := New(
WithIPList(cfg.IPList),
WithCIDRList(cfg.CIDRList),
WithStatusCode(cfg.StatusCode),
WithMessage(cfg.Message),
WithSkipPaths(cfg.SkipPaths),
)
return m.Handler
})
}
init()-based registration is the same self-registering pattern from part 2 — the blank import is the only wiring your main.go will ever see.
Step 4: Drive it from YAML
server:
http:
addr: ":8080"
middleware:
- recovery
- cors
- ip_blocklist # <- our custom middleware, inline with the built-ins
- logger
middleware:
ip_blocklist:
ip_list:
- "192.168.1.100"
- "10.0.0.50"
cidr_list:
- "10.10.0.0/24"
- "172.16.0.0/16"
status_code: 403
message: "Your IP has been blocked"
skip_paths:
- /health
- /metrics
Step 5: Wire and test
package main
import (
_ "github.com/tx7do/go-wind-plugins/transport/http"
_ "github.com/tx7do/go-wind-plugins/log/zap"
_ "my-service/plugins/middleware/ip_blocklist" // <- the whole integration
"github.com/tx7do/go-wind-bootstrap"
)
func main() {
app := bootstrap.New("configs/config.yaml")
app.Run()
}
# Normal request
curl http://localhost:8080/api/users
# 200 OK
# Blocklisted IP (simulated)
curl -H "X-Forwarded-For: 192.168.1.100" http://localhost:8080/api/users
# 403 — Your IP has been blocked
# Inside a blocked CIDR range
curl -H "X-Forwarded-For: 10.10.0.5" http://localhost:8080/api/users
# 403 — Your IP has been blocked
# Health checks stay open even from blocked IPs
curl -H "X-Forwarded-For: 192.168.1.100" http://localhost:8080/health
# 200 OK
Total integration code in main.go: one blank import.
Extension: a dynamic blocklist from Redis
Static YAML is fine for known-bad ranges. For "ban this client for an hour", swap the lookup for a Redis existence check with a TTL:
func (m *DynamicMiddleware) Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
clientIP := extractIP(r)
blocked, _ := m.cache.Exists(r.Context(), "blocklist:"+clientIP)
if blocked {
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte("Your IP has been temporarily blocked"))
return
}
next.ServeHTTP(w, r)
})
}
// Ban an IP for a duration
func BlockIP(ctx context.Context, cache cache.Cache, ip string, duration time.Duration) error {
return cache.Set(ctx, "blocklist:"+ip, []byte("1"), duration)
}
Same SPI registration, same YAML slot in the middleware chain — infrastructure changes without touching the request flow elsewhere.
The shape is the lesson
Every plugin in the framework — cache, broker, gateway, tracer, and the 130+ shipping today — follows this same checklist:
| Check | Why |
|---|---|
Functional options (With*) |
constructor stays stable as config grows |
New(opts ...Option) factory |
nothing global, easy to unit test |
Register* inside init()
|
zero wiring in consumer code |
| YAML config mapping | the config file stays the single source of truth |
A 500-line core isn't a limitation — it's what forces every capability to enter through the same narrow door. That's what keeps 157 modules from collapsing into a big ball of mud.
- Quickstart templates with
_examples/: github.com/tx7do - Plugin registry internals: gowind.cloud/en/framework/plugins-registry.html · SPI mechanism
- Live admin demo: react.admin.gowind.cloud (
admin/Abcd@1234)
Next in the series: zero-trust network access in pure Go — how our SDP product does SPA network stealth, P2P traversal, and SSH/RDP session replay without a JVM in sight. Follow me on DEV so you don't miss it.
GoWind: https://www.gowind.cloud · GitHub: https://github.com/tx7do
Top comments (0)