/
std_ip.go
45 lines (39 loc) · 893 Bytes
/
std_ip.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package function
import (
"net"
"net/netip"
"github.com/ysugimoto/vintage/errors"
"github.com/ysugimoto/vintage/runtime/core"
)
const Std_ip_Name = "std.ip"
// Fastly built-in function implementation of std.ip
// Arguments may be:
// - STRING, STRING
// Reference: https://developer.fastly.com/reference/vcl/functions/strings/std-ip/
func Std_ip[T core.EdgeRuntime](
ctx *core.Runtime[T],
addr, fallback string,
) (net.IP, error) {
ip, err := netip.ParseAddr(addr)
if err != nil {
ip, err = netip.ParseAddr(fallback)
if err != nil {
return nil, errors.FunctionError(
Std_ip_Name,
"Failed to parse IP: %w", err,
)
}
}
switch {
case ip.Is6():
v := ip.As16()
return net.IP(v[:]), nil
case ip.Is4():
v := ip.As4()
return net.IP(v[:]), nil
default:
return nil, errors.FunctionError(
Std_ip_Name, "Unexpected IP string: %s", ip.String(),
)
}
}