poem.go 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // ============================================================================
  2. //go:build !service
  3. // poem.go — 随机古诗
  4. //
  5. // 主窗口首个 Tab(笔记页)footer 内水平滚动显示一首随机古诗;
  6. // 数据来自 poetry.palemoky.com 的随机接口,颜色 / 字号 / 刷新间隔可配置。
  7. // ============================================================================
  8. package main
  9. import (
  10. "encoding/json"
  11. "fmt"
  12. "net/http"
  13. "strings"
  14. "time"
  15. )
  16. const (
  17. PoemAPIURL = "https://poetry.palemoky.com/api/poems/random" // 随机古诗接口
  18. )
  19. // PoemData 一首古诗的完整数据(从接口解析)
  20. type PoemData struct {
  21. Title string `json:"title"` // 题目
  22. Author string `json:"author"` // 作者
  23. Dynasty string `json:"dynasty"` // 朝代
  24. Content []string `json:"content"` // 每句诗(数组,按行显示)
  25. Type string `json:"type"` // 体裁,如 五言律诗
  26. }
  27. // poemAPIResponse 接口返回的外层结构
  28. type poemAPIResponse struct {
  29. Data struct {
  30. ID int `json:"id"`
  31. Title string `json:"title"`
  32. Content []string `json:"content"`
  33. Author struct {
  34. ID int `json:"id"`
  35. Name string `json:"name"`
  36. } `json:"author"`
  37. Dynasty struct {
  38. ID int `json:"id"`
  39. Name string `json:"name"`
  40. } `json:"dynasty"`
  41. Type struct {
  42. ID int `json:"id"`
  43. Name string `json:"name"`
  44. } `json:"type"`
  45. } `json:"data"`
  46. Lang string `json:"lang"`
  47. }
  48. // fetchRandomPoem 从接口拉取一首随机古诗;失败时返回错误
  49. func fetchRandomPoem() (PoemData, error) {
  50. client := &http.Client{Timeout: 10 * time.Second}
  51. resp, err := client.Get(PoemAPIURL)
  52. if err != nil {
  53. return PoemData{}, fmt.Errorf("请求古诗接口失败: %w", err)
  54. }
  55. defer resp.Body.Close()
  56. if resp.StatusCode != http.StatusOK {
  57. return PoemData{}, fmt.Errorf("古诗接口返回状态 %d", resp.StatusCode)
  58. }
  59. var out poemAPIResponse
  60. if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
  61. return PoemData{}, fmt.Errorf("解析古诗数据失败: %w", err)
  62. }
  63. p := PoemData{
  64. Title: strings.TrimSpace(out.Data.Title),
  65. Author: strings.TrimSpace(out.Data.Author.Name),
  66. Dynasty: strings.TrimSpace(out.Data.Dynasty.Name),
  67. Content: out.Data.Content,
  68. Type: strings.TrimSpace(out.Data.Type.Name),
  69. }
  70. if p.Title == "" && len(p.Content) == 0 {
  71. return PoemData{}, fmt.Errorf("古诗接口返回空数据")
  72. }
  73. return p, nil
  74. }
  75. // GetRandomPoem 返回一首随机古诗(供主窗口前端加载 / 手动刷新调用)
  76. func (s *SettingsService) GetRandomPoem() (PoemData, error) {
  77. return fetchRandomPoem()
  78. }