|
| 1 | +package sdk |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "strings" |
| 8 | + "time" |
| 9 | +) |
| 10 | + |
| 11 | +var errCameraHostRequired = errors.New("host is required") |
| 12 | + |
| 13 | +// CameraHTTPClient wraps the shared HTTP request behavior for camera plugins. |
| 14 | +type CameraHTTPClient struct { |
| 15 | + BaseURL string |
| 16 | + Timeout time.Duration |
| 17 | + AuthHeader string |
| 18 | +} |
| 19 | + |
| 20 | +// NewCameraHTTPClient builds a shared HTTP client from camera plugin config. |
| 21 | +func NewCameraHTTPClient(cfg CameraPluginConfig, fallbackTimeout time.Duration) (*CameraHTTPClient, error) { |
| 22 | + host := strings.TrimSpace(cfg.Host) |
| 23 | + if host == "" { |
| 24 | + return nil, errCameraHostRequired |
| 25 | + } |
| 26 | + |
| 27 | + scheme, err := cfg.NormalizedScheme() |
| 28 | + if err != nil { |
| 29 | + return nil, err |
| 30 | + } |
| 31 | + |
| 32 | + return &CameraHTTPClient{ |
| 33 | + BaseURL: fmt.Sprintf("%s://%s", scheme, host), |
| 34 | + Timeout: cfg.ParsedTimeout(fallbackTimeout), |
| 35 | + AuthHeader: cfg.BasicAuthHeader(), |
| 36 | + }, nil |
| 37 | +} |
| 38 | + |
| 39 | +// URL resolves a relative path against the camera base URL. |
| 40 | +func (c *CameraHTTPClient) URL(path string) string { |
| 41 | + if c == nil { |
| 42 | + return path |
| 43 | + } |
| 44 | + |
| 45 | + return c.BaseURL + path |
| 46 | +} |
| 47 | + |
| 48 | +// DoContext performs an HTTP request with the shared auth and timeout settings. |
| 49 | +func (c *CameraHTTPClient) DoContext(ctx context.Context, req HTTPRequest) (*HTTPResponse, error) { |
| 50 | + if c == nil { |
| 51 | + return nil, errCameraHostRequired |
| 52 | + } |
| 53 | + |
| 54 | + if req.URL == "" { |
| 55 | + req.URL = c.BaseURL |
| 56 | + } |
| 57 | + if req.TimeoutMS == 0 { |
| 58 | + req.TimeoutMS = int(c.Timeout.Milliseconds()) |
| 59 | + } |
| 60 | + if c.AuthHeader != "" { |
| 61 | + if req.Headers == nil { |
| 62 | + req.Headers = map[string]string{} |
| 63 | + } |
| 64 | + if _, ok := req.Headers["Authorization"]; !ok { |
| 65 | + req.Headers["Authorization"] = c.AuthHeader |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return HTTP.DoContext(ctx, req) |
| 70 | +} |
| 71 | + |
| 72 | +// GetContext performs a GET request against a relative path. |
| 73 | +func (c *CameraHTTPClient) GetContext(ctx context.Context, path string) (*HTTPResponse, error) { |
| 74 | + return c.DoContext(ctx, HTTPRequest{ |
| 75 | + Method: "GET", |
| 76 | + URL: c.URL(path), |
| 77 | + }) |
| 78 | +} |
0 commit comments