Files
common/ragflow/client.go

161 lines
3.7 KiB
Go
Raw Normal View History

2025-11-27 17:38:42 +08:00
package ragflow
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
2025-12-03 09:59:40 +08:00
"github.com/gogf/gf/v2/frame/g"
2025-11-27 17:38:42 +08:00
"github.com/gogf/gf/v2/net/gclient"
2025-12-03 09:59:40 +08:00
"github.com/gogf/gf/v2/os/gcfg"
2025-11-27 17:38:42 +08:00
)
2025-12-03 09:59:40 +08:00
var (
// globalClient 全局 RAGFlow 客户端(单例,自动初始化)
globalClient *Client
)
// init 包初始化时自动创建全局客户端
func init() {
ctx := context.Background()
2025-11-27 17:38:42 +08:00
2025-12-03 09:59:40 +08:00
// 读取配置
baseURL, apiKey := loadConfig(ctx)
2025-11-27 18:03:01 +08:00
2025-12-03 09:59:40 +08:00
// 如果配置不完整,跳过初始化
if baseURL == "" || apiKey == "" {
g.Log().Warning(ctx, "⚠️ RAGFlow 配置未找到,请在 common/ragflow/config.yaml 中配置")
return
}
// 初始化全局客户端
httpClient := gclient.New()
httpClient.SetHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey))
httpClient.SetHeader("Content-Type", "application/json")
globalClient = &Client{
2025-11-27 17:38:42 +08:00
BaseURL: strings.TrimSuffix(baseURL, "/"),
APIKey: apiKey,
2025-12-03 09:59:40 +08:00
HTTPClient: httpClient,
}
g.Log().Infof(ctx, "✅ RAGFlow 全局客户端初始化成功: baseURL=%s", baseURL)
}
// loadConfig 从配置文件加载 RAGFlow 配置
func loadConfig(ctx context.Context) (baseURL, apiKey string) {
// 创建配置实例
cfg, err := gcfg.New()
if err != nil {
g.Log().Debugf(ctx, "创建配置实例失败: %v", err)
return "", ""
2025-11-27 17:38:42 +08:00
}
2025-12-03 09:59:40 +08:00
// 设置配置文件
adapter, ok := cfg.GetAdapter().(*gcfg.AdapterFile)
if !ok {
g.Log().Debug(ctx, "配置适配器类型不匹配")
return "", ""
}
adapter.SetFileName("config.yaml")
// 读取配置项
baseURL = cfg.MustGet(ctx, "ragflow.base_url").String()
apiKey = cfg.MustGet(ctx, "ragflow.api_key").String()
return baseURL, apiKey
}
// GetGlobalClient 获取全局客户端
// 使用示例client := ragflow.GetGlobalClient()
func GetGlobalClient() *Client {
return globalClient
}
// Client RAGFlow API 客户端
type Client struct {
BaseURL string
APIKey string
HTTPClient *gclient.Client // HTTP 客户端
2025-11-27 17:38:42 +08:00
}
// CommonResponse 通用响应结构
type CommonResponse struct {
2025-11-27 18:03:01 +08:00
Code int `json:"code"`
Message string `json:"message"`
2025-11-27 17:38:42 +08:00
Data interface{} `json:"data,omitempty"`
}
// IsSuccess 检查响应是否成功
func (r *CommonResponse) IsSuccess() bool {
return r.Code == 0
}
// request 发送 HTTP 请求
func (c *Client) request(ctx context.Context, method, path string, body interface{}, result interface{}) error {
fullURL := c.BaseURL + path
2025-11-27 18:03:01 +08:00
2025-11-27 17:38:42 +08:00
var reqBody io.Reader
if body != nil {
jsonData, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("marshal request body failed: %w", err)
}
reqBody = strings.NewReader(string(jsonData))
}
2025-11-27 18:03:01 +08:00
2025-11-27 17:38:42 +08:00
var resp *gclient.Response
var err error
2025-11-27 18:03:01 +08:00
2025-11-27 17:38:42 +08:00
switch method {
case "GET":
resp, err = c.HTTPClient.Get(ctx, fullURL)
case "POST":
resp, err = c.HTTPClient.Post(ctx, fullURL, reqBody)
case "PUT":
resp, err = c.HTTPClient.Put(ctx, fullURL, reqBody)
case "DELETE":
resp, err = c.HTTPClient.Delete(ctx, fullURL, reqBody)
default:
return fmt.Errorf("unsupported method: %s", method)
}
2025-11-27 18:03:01 +08:00
2025-11-27 17:38:42 +08:00
if err != nil {
return fmt.Errorf("http request failed: %w", err)
}
defer resp.Close()
2025-11-27 18:03:01 +08:00
2025-11-27 17:38:42 +08:00
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("http request failed with status: %d", resp.StatusCode)
}
2025-11-27 18:03:01 +08:00
respBody := resp.ReadAll()
2025-11-27 17:38:42 +08:00
if err != nil {
return fmt.Errorf("read response body failed: %w", err)
}
2025-11-27 18:03:01 +08:00
2025-11-27 17:38:42 +08:00
if err := json.Unmarshal(respBody, result); err != nil {
return fmt.Errorf("unmarshal response failed: %w", err)
}
2025-11-27 18:03:01 +08:00
2025-11-27 17:38:42 +08:00
return nil
}
// buildQueryString 构建查询字符串
func buildQueryString(params map[string]interface{}) string {
if len(params) == 0 {
return ""
}
2025-11-27 18:03:01 +08:00
2025-11-27 17:38:42 +08:00
var parts []string
for k, v := range params {
parts = append(parts, fmt.Sprintf("%s=%v", url.QueryEscape(k), url.QueryEscape(fmt.Sprintf("%v", v))))
}
return strings.Join(parts, "&")
}