glider/dns/upstream.go

38 lines
825 B
Go
Raw Normal View History

package dns
import "sync/atomic"
2020-05-06 20:10:18 +08:00
// UPStream is a dns upstream.
type UPStream struct {
index uint32
servers []string
}
2020-05-06 20:10:18 +08:00
// NewUPStream returns a new UpStream.
func NewUPStream(servers []string) *UPStream {
return &UPStream{servers: servers}
}
// Server returns a dns server.
2020-05-06 20:10:18 +08:00
func (u *UPStream) Server() string {
return u.servers[atomic.LoadUint32(&u.index)%uint32(len(u.servers))]
}
// Switch switches to the next dns server.
2020-05-06 20:10:18 +08:00
func (u *UPStream) Switch() string {
return u.servers[atomic.AddUint32(&u.index, 1)%uint32(len(u.servers))]
}
// SwitchIf switches to the next dns server if needed.
2020-05-06 20:10:18 +08:00
func (u *UPStream) SwitchIf(server string) string {
if u.Server() == server {
return u.Switch()
}
return u.Server()
}
// Len returns the number of dns servers.
2020-05-06 20:10:18 +08:00
func (u *UPStream) Len() int {
return len(u.servers)
}