Files
TaskPool/internal/constant/sentence.go
T

91 lines
1.7 KiB
Go
Raw Normal View History

2025-12-20 12:00:08 +08:00
package constant
import (
2025-12-20 12:59:37 +08:00
"bytes"
_ "embed"
2025-12-20 12:00:08 +08:00
"encoding/json"
"math/rand"
"sync"
)
2025-12-20 12:59:37 +08:00
//go:embed sentence1-10000.json
var sentenceData []byte
2025-12-20 12:00:08 +08:00
type Sentence struct {
Name string `json:"name"`
From string `json:"from"`
}
var (
2026-01-21 20:09:50 +08:00
lineCount int
lineOffsets []int64
sentenceOnce sync.Once
2025-12-20 12:00:08 +08:00
)
2025-12-20 12:59:37 +08:00
// initSentences 初始化:统计行数和记录每行偏移
func initSentences() {
sentenceOnce.Do(func() {
2026-04-30 09:01:02 +08:00
data := sentenceData
2025-12-20 12:59:37 +08:00
var offset int64 = 0
2026-04-30 09:01:02 +08:00
for {
// 记录当前行的起始位置
2025-12-20 12:59:37 +08:00
lineOffsets = append(lineOffsets, offset)
2025-12-20 12:00:08 +08:00
lineCount++
2026-04-30 09:01:02 +08:00
// 寻找下一个换行符
idx := bytes.IndexByte(data[offset:], '\n')
if idx == -1 {
// 最后一行没有换行符
break
}
// 移动到下一行的起始位置
offset += int64(idx) + 1
if offset >= int64(len(data)) {
break
}
2025-12-20 12:00:08 +08:00
}
})
}
// GetRandomSentence 随机获取一条古诗词
func GetRandomSentence() string {
2025-12-20 12:59:37 +08:00
initSentences()
2026-04-30 09:01:02 +08:00
if lineCount <= 0 {
2025-12-20 12:00:08 +08:00
return "欢迎使用白虎面板"
}
2026-04-22 21:36:56 +08:00
targetIndex := rand.Intn(lineCount)
start := lineOffsets[targetIndex]
2026-01-21 20:09:50 +08:00
2026-04-30 09:01:02 +08:00
// 确定当前行的结束位置
2026-04-22 21:36:56 +08:00
var end int64
if targetIndex < lineCount-1 {
2026-04-30 09:01:02 +08:00
end = lineOffsets[targetIndex+1]
2026-04-22 21:36:56 +08:00
} else {
end = int64(len(sentenceData))
}
2026-04-30 09:01:02 +08:00
// 提取行并清理两端的空白字符(包括 \r, \n)
line := bytes.TrimSpace(sentenceData[start:end])
if len(line) == 0 {
return "欢迎使用白虎面板"
}
2026-04-22 21:36:56 +08:00
var sData []string
if err := json.Unmarshal(line, &sData); err == nil && len(sData) >= 1 {
name := sData[0]
from := ""
if len(sData) >= 2 {
from = sData[1]
2025-12-20 12:00:08 +08:00
}
2026-04-22 21:36:56 +08:00
if from != "" {
return "\"" + name + "\"—— " + from
}
return name
2025-12-20 12:00:08 +08:00
}
return "欢迎使用白虎面板"
}