refactor: 将歌曲哈希查询方法提取到公共工具包中

This commit is contained in:
lixiangwuxian
2025-03-09 00:07:24 +08:00
parent 5dfc935f18
commit 7d5b69685b
3 changed files with 63 additions and 102 deletions

59
util/song_id.go Normal file
View File

@@ -0,0 +1,59 @@
package util
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strings"
)
func GetSongIdsByHash(hashs []string) (hashToSongId map[string]string, err error) {
if len(hashs) == 0 {
return nil, nil
}
//每批最多49个
hashToSongId = make(map[string]string)
batchSize := 49
for i := 0; i < len(hashs); i += batchSize {
end := i + batchSize
if end > len(hashs) {
end = len(hashs)
}
batchHashs := hashs[i:end]
queryUrl := "https://api.beatsaver.com/maps/hash/" + strings.Join(batchHashs, ",")
log.Default().Printf("获取歌曲IDurl:%s", queryUrl)
resp, err := http.Get(queryUrl)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("获取歌曲ID失败状态码%d,url:%s", resp.StatusCode, queryUrl)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var response = make(map[string]struct {
ID string `json:"id"`
})
if len(batchHashs) == 1 {
var singleResponse struct {
ID string `json:"id"`
}
err = json.Unmarshal(body, &singleResponse)
response[batchHashs[0]] = singleResponse
} else {
err = json.Unmarshal(body, &response)
}
if err != nil {
return nil, err
}
for hash, data := range response {
hashToSongId[hash] = data.ID
}
}
return hashToSongId, nil
}