⚙️ 选项 Options
pkg/repository.Options 是 Repository 层的配置结构,控制 HTTP 请求的服务地址与代理。
结构定义
go
package repository
type Options struct {
ServerUrl string
Proxy string
}| 字段 | 类型 | 说明 |
|---|---|---|
ServerUrl | string | Packagist 服务地址,默认 https://packagist.org |
Proxy | string | HTTP 代理地址,留空表示直连 |
如何生效
Repository.getBytes 在发起请求前检查 Proxy:
go
func (x *Repository) getBytes(ctx context.Context, targetUrl string) ([]byte, error) {
options := requests.NewOptions[any, []byte](targetUrl, requests.BytesResponseHandler())
if x.options.Proxy != "" {
options.AppendRequestSetting(requests.RequestSettingProxy(x.options.Proxy))
}
return requests.SendRequest[any, []byte](ctx, options)
}Proxy非空 → 通过requests.RequestSettingProxy启用代理。ServerUrl在当前Repository实现中未直接使用 —— 方法参数本身已是完整 URL。它主要供上层或未来扩展使用。
字段未导出
Repository.options 是未导出字段,外部包无法直接设置。当前从外部构造 Repository 只能用零值 &repository.Repository{},因此 Options 的代理能力暂仅对包内可用。
如需从外部配置代理/服务地址,请使用 pkg/client.ComposerClient,它提供 WithBaseURL、WithRepoURL、WithAPICredentials 等公开选项。
推荐做法:用 Client 代替
如果你需要配置代理或自定义端点,ComposerClient 才是面向外部的高层门面:
go
package main
import (
"fmt"
"time"
"github.com/scagogogo/composer-skills/pkg/client"
)
func main() {
c := client.NewComposerClient(
30*time.Second,
client.WithBaseURL("https://packagist.org"),
client.WithRepoURL("https://repo.packagist.org"),
client.WithAPICredentials("your-username", "your-api-token"),
)
stats, _ := c.GetStatistics()
fmt.Printf("总包数: %d\n", stats.Packages)
}详见 Client。
进阶
- Repository 层方法:见 Repository。
- 代理在网络受限的 CI 环境中很常见 —— 见 CI/CD 流水线。