package extension import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "net/url" "strings" "time" ) // HostClient 是 sidecar / 外部进程调用基座 Host API 的客户端。 type HostClient struct { BaseURL string Token string PluginID string Owner string HTTP *http.Client } // NewHostClient 用基座注入的地址和令牌构造客户端。 func NewHostClient(baseURL, token, pluginID, owner string) *HostClient { return &HostClient{ BaseURL: strings.TrimRight(baseURL, "/"), Token: token, PluginID: pluginID, Owner: owner, HTTP: &http.Client{Timeout: 30 * time.Second}, } } func (c *HostClient) PutKV(ctx context.Context, key, value string) error { return c.do(ctx, http.MethodPut, "/host/v1/kv/"+url.PathEscape(key), strings.NewReader(value), nil) } func (c *HostClient) GetKV(ctx context.Context, key string) (string, error) { var out struct { Value string `json:"value"` } if err := c.do(ctx, http.MethodGet, "/host/v1/kv/"+url.PathEscape(key), nil, &out); err != nil { return "", err } return out.Value, nil } func (c *HostClient) Audit(ctx context.Context, action, target string, evidence json.RawMessage) error { body, _ := json.Marshal(map[string]any{"action": action, "target": target, "evidence": string(evidence)}) return c.do(ctx, http.MethodPost, "/host/v1/audit", bytes.NewReader(body), nil) } func (c *HostClient) Dispatch(ctx context.Context, commandID string, params map[string]any) error { body, _ := json.Marshal(map[string]any{"params": params}) return c.do(ctx, http.MethodPost, "/host/v1/commands/"+url.PathEscape(commandID), bytes.NewReader(body), nil) } func (c *HostClient) do(ctx context.Context, method, path string, body io.Reader, dest any) error { req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+path, body) if err != nil { return err } if c.Token != "" { req.Header.Set("Authorization", "Bearer "+c.Token) } if c.PluginID != "" { req.Header.Set("X-Plugin-Id", c.PluginID) } if c.Owner != "" { req.Header.Set("X-Owner", c.Owner) } if body != nil { req.Header.Set("Content-Type", "application/json") } client := c.HTTP if client == nil { client = http.DefaultClient } resp, err := client.Do(req) if err != nil { return err } defer resp.Body.Close() raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if resp.StatusCode >= 300 { return fmt.Errorf("host api %s %s: %d %s", method, path, resp.StatusCode, strings.TrimSpace(string(raw))) } if dest != nil && len(raw) > 0 { if err := json.Unmarshal(raw, dest); err != nil { return err } } return nil }