Files
TaskPool/internal/constant/sentence.go
T

66 lines
1.2 KiB
Go
Raw Normal View History

2025-12-20 12:00:08 +08:00
package constant
import (
"bufio"
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() {
scanner := bufio.NewScanner(bytes.NewReader(sentenceData))
var offset int64 = 0
2025-12-20 12:00:08 +08:00
for scanner.Scan() {
2025-12-20 12:59:37 +08:00
lineOffsets = append(lineOffsets, offset)
offset += int64(len(scanner.Bytes())) + 1 // +1 for newline
2025-12-20 12:00:08 +08:00
lineCount++
}
})
}
// GetRandomSentence 随机获取一条古诗词
func GetRandomSentence() string {
2025-12-20 12:59:37 +08:00
initSentences()
2025-12-20 12:00:08 +08:00
if lineCount == 0 {
return "欢迎使用白虎面板"
}
targetLine := rand.Intn(lineCount)
2026-01-21 20:09:50 +08:00
2025-12-20 12:59:37 +08:00
scanner := bufio.NewScanner(bytes.NewReader(sentenceData))
2025-12-20 12:00:08 +08:00
currentLine := 0
for scanner.Scan() {
if currentLine == targetLine {
var s Sentence
if err := json.Unmarshal(scanner.Bytes(), &s); err == nil && s.Name != "" {
2026-01-21 20:09:50 +08:00
if s.From != "" {
return "\"" + s.Name + "\"—— " + s.From
}
2025-12-20 12:00:08 +08:00
return s.Name
}
break
}
currentLine++
}
return "欢迎使用白虎面板"
}