mirror of
https://github.com/woodchen-ink/random-api-go.git
synced 2025-07-18 05:42:01 +08:00
refactor(main): 取消算法, 改成完全随机simplify URLSelector and remove unnecessary fields
This commit is contained in:
parent
749cd088b7
commit
147bda8251
34
main.go
34
main.go
@ -23,7 +23,6 @@ import (
|
|||||||
const (
|
const (
|
||||||
port = ":5003"
|
port = ":5003"
|
||||||
requestTimeout = 10 * time.Second
|
requestTimeout = 10 * time.Second
|
||||||
noRepeatCount = 3 // 在这个次数内不重复选择
|
|
||||||
envBaseURL = "BASE_URL"
|
envBaseURL = "BASE_URL"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -36,17 +35,13 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type URLSelector struct {
|
type URLSelector struct {
|
||||||
URLs []string
|
URLs []string
|
||||||
CurrentIndex int
|
mu sync.Mutex
|
||||||
RecentUsed map[string]int
|
|
||||||
mu sync.Mutex
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewURLSelector(urls []string) *URLSelector {
|
func NewURLSelector(urls []string) *URLSelector {
|
||||||
return &URLSelector{
|
return &URLSelector{
|
||||||
URLs: urls,
|
URLs: urls,
|
||||||
CurrentIndex: 0,
|
|
||||||
RecentUsed: make(map[string]int),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -61,27 +56,10 @@ func (us *URLSelector) GetRandomURL() string {
|
|||||||
us.mu.Lock()
|
us.mu.Lock()
|
||||||
defer us.mu.Unlock()
|
defer us.mu.Unlock()
|
||||||
|
|
||||||
if us.CurrentIndex == 0 {
|
if len(us.URLs) == 0 {
|
||||||
us.ShuffleURLs()
|
return ""
|
||||||
}
|
}
|
||||||
|
return us.URLs[rng.Intn(len(us.URLs))]
|
||||||
for i := 0; i < len(us.URLs); i++ {
|
|
||||||
url := us.URLs[us.CurrentIndex]
|
|
||||||
us.CurrentIndex = (us.CurrentIndex + 1) % len(us.URLs)
|
|
||||||
|
|
||||||
if us.RecentUsed[url] < noRepeatCount {
|
|
||||||
us.RecentUsed[url]++
|
|
||||||
// 如果某个URL使用次数达到上限,从RecentUsed中移除
|
|
||||||
if us.RecentUsed[url] == noRepeatCount {
|
|
||||||
delete(us.RecentUsed, url)
|
|
||||||
}
|
|
||||||
return url
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果所有URL都被最近使用过,重置RecentUsed并返回第一个URL
|
|
||||||
us.RecentUsed = make(map[string]int)
|
|
||||||
return us.URLs[0]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user