1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
}
|