MCPcopy Create free account
hub / github.com/astercloud/aster / Call

Method Call

pkg/sandbox/remote.go:50–100  ·  view source on GitHub ↗

Call 调用远程 API

(ctx context.Context, method, path string, body any)

Source from the content-addressed store, hash-verified

48
49// Call 调用远程 API
50func (rc *RemoteClient) Call(ctx context.Context, method, path string, body any) (*RemoteResponse, error) {
51 var reqBody io.Reader
52 if body != nil {
53 jsonData, err := json.Marshal(body)
54 if err != nil {
55 return nil, fmt.Errorf("marshal request: %w", err)
56 }
57 reqBody = bytes.NewReader(jsonData)
58 }
59
60 url := rc.baseURL + path
61 req, err := http.NewRequestWithContext(ctx, method, url, reqBody)
62 if err != nil {
63 return nil, fmt.Errorf("create request: %w", err)
64 }
65
66 // 设置通用请求头
67 req.Header.Set("Content-Type", "application/json")
68 if rc.apiKey != "" {
69 req.Header.Set("X-Api-Key", rc.apiKey)
70 }
71
72 // 设置自定义请求头
73 for k, v := range rc.headers {
74 req.Header.Set(k, v)
75 }
76
77 // 发送请求
78 resp, err := rc.httpClient.Do(req)
79 if err != nil {
80 return nil, fmt.Errorf("send request: %w", err)
81 }
82 defer func() { _ = resp.Body.Close() }()
83
84 // 读取响应
85 respBody, err := io.ReadAll(resp.Body)
86 if err != nil {
87 return nil, fmt.Errorf("read response: %w", err)
88 }
89
90 // 检查状态码
91 if resp.StatusCode >= 400 {
92 return nil, fmt.Errorf("api error: %d - %s", resp.StatusCode, string(respBody))
93 }
94
95 return &RemoteResponse{
96 StatusCode: resp.StatusCode,
97 Body: respBody,
98 Headers: resp.Header,
99 }, nil
100}
101
102// RemoteResponse 远程响应
103type RemoteResponse struct {

Callers

nothing calls this directly

Calls 2

SetMethod · 0.65
CloseMethod · 0.65

Tested by

no test coverage detected