X-Forwarded-For handler for labstack echo and Fastly

This commit is contained in:
2023-11-12 15:51:21 -08:00
parent 62e28b71f1
commit 2bff6d8ef3
3 changed files with 75 additions and 0 deletions

51
xff/fastlyxff/xff.go Normal file
View File

@@ -0,0 +1,51 @@
package fastlyxff
import (
"encoding/json"
"net"
"net/netip"
"os"
"github.com/labstack/echo/v4"
)
type FastlyXFF struct {
IPv4 []string `json:"addresses"`
IPv6 []string `json:"ipv6_addresses"`
}
type TrustedNets struct {
prefixes []netip.Prefix
}
func New(fileName string) (*FastlyXFF, error) {
b, err := os.ReadFile(fileName)
if err != nil {
return nil, err
}
d := FastlyXFF{}
err = json.Unmarshal(b, &d)
if err != nil {
return nil, err
}
return &d, nil
}
func (xff *FastlyXFF) EchoTrustOption() ([]echo.TrustOption, error) {
ranges := []echo.TrustOption{}
for _, s := range append(xff.IPv4, xff.IPv6...) {
_, cidr, err := net.ParseCIDR(s)
if err != nil {
return nil, err
}
trust := echo.TrustIPRange(cidr)
ranges = append(ranges, trust)
}
return ranges, nil
}