Files
example-eino/pkg/provider/client.go
T
zhaoyupeng.elqbandTRAE CLI 81deca8c8e feat: initialize Eino examples and ADK applications
Include chat, weather, image, travel, streaming ASR and text examples,
shared model initialization, documentation, and existing tests.

Co-authored-by: TRAE CLI <traecli@bytedance.com>
2026-11-19 11:08:03 +08:00

53 lines
1.4 KiB
Go

package provider
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
// httpClient 由所有 provider 请求共用。
var httpClient = &http.Client{}
// PostJSON 发送 JSON 请求,将响应解码到 result,并检查 HTTP 状态码。
func PostJSON(ctx context.Context, endpoint string, headers map[string]string, body, result any) error {
resp, err := PostJSONResponse(ctx, endpoint, headers, body)
if err != nil {
return err
}
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(result)
}
// PostJSONResponse 发送 JSON 请求并检查状态码,调用方负责关闭响应体。
func PostJSONResponse(ctx context.Context, endpoint string, headers map[string]string, body any) (*http.Response, error) {
data, err := json.Marshal(body)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(data))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
for key, value := range headers {
req.Header.Set(key, value)
}
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("接口返回 %s,读取错误信息失败: %w", resp.Status, err)
}
return nil, fmt.Errorf("接口返回 %s: %s", resp.Status, data)
}
return resp, nil
}