Cache public IP for 5 min
This commit is contained in:
+20
-1
@@ -9,6 +9,7 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewCandidate(address string) (string, error) {
|
func NewCandidate(address string) (string, error) {
|
||||||
@@ -38,7 +39,7 @@ func NewCandidate(address string) (string, error) {
|
|||||||
|
|
||||||
func LookupIP(address string) (string, error) {
|
func LookupIP(address string) (string, error) {
|
||||||
if strings.HasPrefix(address, "stun:") {
|
if strings.HasPrefix(address, "stun:") {
|
||||||
ip, err := GetPublicIP()
|
ip, err := GetCachedPublicIP()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
@@ -99,6 +100,24 @@ func GetPublicIP() (net.IP, error) {
|
|||||||
return xorAddr.IP, nil
|
return xorAddr.IP, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var cachedIP net.IP
|
||||||
|
var cachedTS time.Time
|
||||||
|
|
||||||
|
func GetCachedPublicIP() (net.IP, error) {
|
||||||
|
now := time.Now()
|
||||||
|
if now.After(cachedTS) {
|
||||||
|
newIP, err := GetPublicIP()
|
||||||
|
if err == nil {
|
||||||
|
cachedIP = newIP
|
||||||
|
cachedTS = now.Add(time.Minute * 5)
|
||||||
|
} else if cachedIP == nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return cachedIP, nil
|
||||||
|
}
|
||||||
|
|
||||||
func IsIP(host string) bool {
|
func IsIP(host string) bool {
|
||||||
for _, i := range host {
|
for _, i := range host {
|
||||||
if i >= 'A' {
|
if i >= 'A' {
|
||||||
|
|||||||
Reference in New Issue
Block a user