github.com/qiniu/go-sdk/v7@v7.27.0/storagev2/chooser/smart_ip_chooser.go (about) 1 package chooser 2 3 import ( 4 "context" 5 "net" 6 ) 7 8 type ( 9 smartIPChooser struct { 10 ipChooser, subnetChooser Chooser 11 } 12 13 // SmartIPChooserConfig 智能 IP 选择器的选项 14 SmartIPChooserConfig IPChooserConfig 15 ) 16 17 // NewSmartIPChooser 创建智能 IP 选择器 18 func NewSmartIPChooser(options *SmartIPChooserConfig) Chooser { 19 return &smartIPChooser{ 20 ipChooser: NewIPChooser((*IPChooserConfig)(options)), 21 subnetChooser: NewSubnetChooser((*SubnetChooserConfig)(options)), 22 } 23 } 24 25 func (chooser *smartIPChooser) Choose(ctx context.Context, ips []net.IP, options *ChooseOptions) []net.IP { 26 if chooser.allInSingleSubnet(ips) { 27 return chooser.ipChooser.Choose(ctx, ips, options) 28 } else { 29 return chooser.subnetChooser.Choose(ctx, ips, options) 30 } 31 } 32 33 func (chooser *smartIPChooser) FeedbackGood(ctx context.Context, ips []net.IP, options *FeedbackOptions) { 34 chooser.ipChooser.FeedbackGood(ctx, ips, options) 35 chooser.subnetChooser.FeedbackGood(ctx, ips, options) 36 } 37 38 func (chooser *smartIPChooser) FeedbackBad(ctx context.Context, ips []net.IP, options *FeedbackOptions) { 39 chooser.ipChooser.FeedbackBad(ctx, ips, options) 40 chooser.subnetChooser.FeedbackBad(ctx, ips, options) 41 } 42 43 func (chooser *smartIPChooser) allInSingleSubnet(ips []net.IP) bool { 44 var subnet net.IP 45 for i, ip := range ips { 46 if i == 0 { 47 subnet = makeSubnet(ip) 48 } else if !subnet.Equal(makeSubnet(ip)) { 49 return false 50 } 51 } 52 return true 53 }