📊 统计
获取 Packagist 仓库的整体统计数据:总下载量、包总数、版本总数。适合做生态概览、增长趋势监控、首页数据展示。
何时使用
- 📈 在仪表盘首页展示 Packagist 生态规模(「已收录 N 个包,累计下载 M 次」)。
- 📊 定期采集统计,绘制生态增长曲线。
- 🧪 健康检查:快速验证能否正常访问 Packagist。
- 🔍 与自建镜像的本地数据对比,确认同步完整性。
数据模型
StatisticsResponse
pkg/domain/statistics.go,对应 https://packagist.org/statistics.json 响应。
go
type StatisticsResponse struct {
Totals Totals `json:"totals"`
}| 字段 | 类型 | 说明 |
|---|---|---|
Totals | Totals | 仓库总计统计 |
Totals
go
type Totals struct {
Downloads int64 `json:"downloads"`
Packages int `json:"packages"`
Versions int `json:"versions"`
}| 字段 | 类型 | 说明 |
|---|---|---|
Downloads | int64 | 所有包的总下载次数(值很大,用 int64 容纳) |
Packages | int | 仓库中的包总数 |
Versions | int | 所有包的版本总数 |
为什么 Downloads 用 int64?
Packagist 累计下载量早已超过 int32 上限(约 21 亿),因此该字段使用 int64,避免在 32 位平台溢出。
GetStatistics
📊 获取 Packagist 仓库的整体统计信息。对应 GET https://packagist.org/statistics.json。
签名
go
func (c *ComposerClient) GetStatistics() (*domain.StatisticsResponse, error)参数
无。
返回值
| 值 | 类型 | 说明 |
|---|---|---|
| 结果 | *domain.StatisticsResponse | 含 Totals(下载/包/版本总数) |
| 错误 | error | HTTP 失败、非 200、JSON 解析失败时返回 |
示例
go
package main
import (
"fmt"
"log"
"time"
"github.com/scagogogo/composer-skills/pkg/client"
)
func main() {
c := client.NewComposerClient(30 * time.Second)
stats, err := c.GetStatistics()
if err != nil {
log.Fatalf("获取统计失败: %v", err)
}
fmt.Printf("累计下载: %d\n", stats.Totals.Downloads)
fmt.Printf("包总数: %d\n", stats.Totals.Packages)
fmt.Printf("版本总数: %d\n", stats.Totals.Versions)
}输出示例:
text
累计下载: 12345678901
包总数: 395421
版本总数: 2876543进阶
作为健康探针
GetStatistics 无参数、响应小、端点稳定,非常适合作为「能否访问 Packagist」的探针:
go
func checkPackagist(c *client.ComposerClient) bool {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// 注意:GetStatistics 本身不接受 ctx,这里仅做超时演示;
// 如需 ctx 控制,改用底层 Repository.Statistics(ctx)。
_, err := c.GetStatistics()
return err == nil
}不接受 context
ComposerClient.GetStatistics() 签名不含 context.Context,超时由 NewComposerClient(timeout) 传入的整体超时控制。若需要请求级取消 / 超时,请改用底层 Repository.Statistics(ctx),它接受 context.Context。
🔗 相关
- 📦 单个包的下载统计见 GetPackageStats。
- 🏗️ 底层实现见 Repository.Statistics。