go 36 lines · 1 tab

CIDR allowlist middleware using netip (trust boundary explicit)

Leah Thompson Jan 2026
1 tab
package middleware

import (
  "net"
  "net/http"
  "net/netip"
)

func AllowCIDRs(prefixes []netip.Prefix) func(http.Handler) http.Handler {
  return func(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
      host, _, err := net.SplitHostPort(r.RemoteAddr)
      if err != nil {
        http.Error(w, "forbidden", http.StatusForbidden)
        return
      }
      addr, err := netip.ParseAddr(host)
      if err != nil {
        http.Error(w, "forbidden", http.StatusForbidden)
        return
      }
      ok := false
      for _, p := range prefixes {
        if p.Contains(addr) {
          ok = true
          break
        }
      }
      if !ok {
        http.Error(w, "forbidden", http.StatusForbidden)
        return
      }
      next.ServeHTTP(w, r)
    })
  }
}
1 file · go Explain with highlit

For internal admin endpoints, I often add a network allowlist in addition to auth. The tricky part is deciding which IP to trust: if you’re behind a proxy, you might need X-Forwarded-For, but only if the proxy is controlled by you. The middleware below parses CIDRs into netip.Prefix and checks whether the client address falls inside. I keep the allowlist immutable and fail closed: if the IP can’t be parsed, access is denied. In production, I also log denials with a request ID so you can debug misconfigured proxies without printing sensitive headers. The key is to treat this as a defense-in-depth layer, not your only protection.


Related snips

Share this code

Here's the card — post it anywhere.

CIDR allowlist middleware using netip (trust boundary explicit) — share card
Link copied