修改GetRandomSatisfiedChannel函数,添加渠道标签过滤参数
(group string, model string, retry int, channelTag *string)
| 104 | |
| 105 | // 修改GetRandomSatisfiedChannel函数,添加渠道标签过滤参数 |
| 106 | func GetRandomSatisfiedChannel(group string, model string, retry int, channelTag *string) (*Channel, error) { |
| 107 | var abilities []Ability |
| 108 | |
| 109 | var err error = nil |
| 110 | channelQuery, err := getChannelQuery(group, model, retry) |
| 111 | if err != nil { |
| 112 | return nil, err |
| 113 | } |
| 114 | |
| 115 | // 如果提供了渠道标签,则添加标签过滤条件 |
| 116 | if channelTag != nil && *channelTag != "" { |
| 117 | channelQuery = channelQuery.Where("tag = ? OR tag IS NULL", *channelTag) |
| 118 | } |
| 119 | |
| 120 | if common.UsingSQLite || common.UsingPostgreSQL { |
| 121 | err = channelQuery.Order("weight DESC").Find(&abilities).Error |
| 122 | } else { |
| 123 | err = channelQuery.Order("weight DESC").Find(&abilities).Error |
| 124 | } |
| 125 | if err != nil { |
| 126 | return nil, err |
| 127 | } |
| 128 | |
| 129 | // 过滤符合标签要求的渠道 |
| 130 | var filteredAbilities []Ability |
| 131 | for _, ability := range abilities { |
| 132 | // 如果提供了渠道标签,只考虑匹配标签的渠道 |
| 133 | if channelTag != nil && *channelTag != "" { |
| 134 | // 如果渠道标签不匹配,则跳过 |
| 135 | if ability.Tag != nil && *ability.Tag != "" && *ability.Tag != *channelTag { |
| 136 | continue |
| 137 | } |
| 138 | } |
| 139 | filteredAbilities = append(filteredAbilities, ability) |
| 140 | } |
| 141 | |
| 142 | // 如果没有符合条件的渠道,返回错误 |
| 143 | if len(filteredAbilities) == 0 { |
| 144 | if channelTag != nil && *channelTag != "" { |
| 145 | return nil, fmt.Errorf("没有找到标签为 '%s' 的可用渠道", *channelTag) |
| 146 | } |
| 147 | return nil, errors.New("channel not found") |
| 148 | } |
| 149 | |
| 150 | channel := Channel{} |
| 151 | if len(filteredAbilities) > 0 { |
| 152 | // Randomly choose one based on weight |
| 153 | weightSum := uint(0) |
| 154 | for _, ability := range filteredAbilities { |
| 155 | weightSum += ability.Weight + 10 // 平滑系数 |
| 156 | } |
| 157 | |
| 158 | // 如果总权重为0,则平均分配权重 |
| 159 | if weightSum == 0 { |
| 160 | // 随机选择一个渠道 |
| 161 | randomIndex := common.GetRandomInt(len(filteredAbilities)) |
| 162 | channel.Id = filteredAbilities[randomIndex].ChannelId |
| 163 | } else { |
no test coverage detected