From c52f41545df179b542f106d08e6dd013a70216e7 Mon Sep 17 00:00:00 2001 From: yingyu5658 Date: Thu, 4 Dec 2025 11:19:57 +0800 Subject: refactor: 模块化重构并优化输出 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将原本的 main.go 拆分为 命令 网络请求 下载三个单独职责的文件 - 优化输出, 添加用户友好的Emoji --- internal/api/biliapi.go | 94 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 internal/api/biliapi.go (limited to 'internal/api/biliapi.go') diff --git a/internal/api/biliapi.go b/internal/api/biliapi.go new file mode 100644 index 0000000..efd2499 --- /dev/null +++ b/internal/api/biliapi.go @@ -0,0 +1,94 @@ +package api + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "time" +) + +type VideoBaseInfo struct { + Data []struct { + Cid int `json:"cid"` // 每一个视频的 CID + Part string `json:"part"` // 分 P 标题 + Page int `json:"page"` // 分 P 编号 + FirstFrame string `json:"first_frame"` // 封面图 + } `json:"data"` +} + +type BiliAPI struct { + Client *http.Client +} + +func NewBiliAPI() *BiliAPI { + return &BiliAPI{ + Client: &http.Client{Timeout: 30 * time.Second}, + } +} + +// func getInfo(bvid string) (VideoBaseInfo, error) { +// var APIUrl string = "https://api.bilibili.com/x/player/pagelist?bvid=" +// APIUrl += bvid +// client := &http.Client{ +// Timeout: 30 * time.Second, +// } + +// // 发送 GET 请求 +// resp, err := client.Get(APIUrl) +// if err != nil { +// return VideoBaseInfo{}, fmt.Errorf("发送请求失败: %w", err) +// } +// defer resp.Body.Close() + +// body, err := io.ReadAll(resp.Body) +// if err != nil { +// return VideoBaseInfo{}, fmt.Errorf("读取响应失败: %w", err) +// } + +// var result VideoBaseInfo +// if err := json.Unmarshal(body, &result); err != nil { +// return VideoBaseInfo{}, fmt.Errorf("JSON 解析失败: %w", err) +// } + +// return VideoBaseInfo{}, err +// } + +func (a *BiliAPI) GetVideoInfo(bvid string) (*VideoBaseInfo, error) { + var APIUrl string = "https://api.bilibili.com/x/player/pagelist?bvid=" + APIUrl += bvid + client := a.Client + if client == nil { + client = &http.Client{ + Timeout: 30 * time.Second, + } + } + + // 发送 GET 请求 + resp, err := client.Get(APIUrl) + if err != nil { + return &VideoBaseInfo{}, fmt.Errorf("❌ 发送请求失败: %w", err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return &VideoBaseInfo{}, fmt.Errorf("❌ 读取响应失败: %w", err) + } + + if len(body) > 0 && body[0] == '<' { + snippet := string(body) + if len(snippet) > 512 { + snippet = snippet[:512] + } + return nil, fmt.Errorf("❌ 服务器返回 HTML 而非 JSON: %s", snippet) + } + + var result VideoBaseInfo + if err := json.Unmarshal(body, &result); err != nil { + return &VideoBaseInfo{}, fmt.Errorf("❌ JSON 解析失败: %w", err) + } + + return &result, nil + +} -- cgit v1.2.3