|
| 1 | +/* |
| 2 | +@Time : 2025/5/7 12:27 |
| 3 | +@Author : dongdongliu |
| 4 | +@File : k2 |
| 5 | +@Version: 1.0 |
| 6 | +@Software: GoLand |
| 7 | +*/ |
| 8 | +package k2 |
| 9 | + |
| 10 | +import ( |
| 11 | + "context" |
| 12 | + "fmt" |
| 13 | + "github.com/opendevops-cn/codo-golang-sdk/client/xhttp" |
| 14 | + "github.com/opendevops-cn/codo-golang-sdk/consts" |
| 15 | + "net/http" |
| 16 | +) |
| 17 | + |
| 18 | +type NoAuthConfig struct { |
| 19 | + url string |
| 20 | + client xhttp.IClient |
| 21 | +} |
| 22 | + |
| 23 | +type AuthConfig struct { |
| 24 | + url string |
| 25 | + authKey string |
| 26 | + client xhttp.IClient |
| 27 | + cookies []*http.Cookie |
| 28 | +} |
| 29 | + |
| 30 | +func NewNoAuthConfig(url string, client xhttp.IClient) *NoAuthConfig { |
| 31 | + return &NoAuthConfig{ |
| 32 | + url: url, |
| 33 | + client: client, |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +func NewAuthConfig(url, authKey string, client xhttp.IClient) *AuthConfig { |
| 38 | + Cookie := &http.Cookie{ |
| 39 | + Name: consts.CODOAPIGatewayAuthKeyHeader, |
| 40 | + Value: authKey, |
| 41 | + } |
| 42 | + return &AuthConfig{ |
| 43 | + url: url, |
| 44 | + client: client, |
| 45 | + cookies: []*http.Cookie{Cookie}, |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +func (x *NoAuthConfig) GetConfig(ctx context.Context) (*http.Response, error) { |
| 50 | + req, err := http.NewRequestWithContext(ctx, "GET", x.url, nil) |
| 51 | + if err != nil { |
| 52 | + return nil, fmt.Errorf("build request err: %w", err) |
| 53 | + } |
| 54 | + return x.client.Do(ctx, req) |
| 55 | +} |
| 56 | + |
| 57 | +func (x *AuthConfig) GetConfig(ctx context.Context) (*http.Response, error) { |
| 58 | + req, err := http.NewRequestWithContext(ctx, "GET", x.url, nil) |
| 59 | + if err != nil { |
| 60 | + return nil, fmt.Errorf("build request err: %w", err) |
| 61 | + } |
| 62 | + // 自动添加统一设置的 Cookie |
| 63 | + for _, cookie := range x.cookies { |
| 64 | + req.AddCookie(cookie) |
| 65 | + } |
| 66 | + return x.client.Do(ctx, req) |
| 67 | +} |
0 commit comments