Files
common/ragflow/client.go
T
2026-03-12 08:51:25 +08:00

115 lines
2.8 KiB
Go

package ragflow
import (
"context"
"net/url"
"strings"
"sync"
commonHttp "gitee.com/red-future---jilin-g/common/http"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
)
var (
// globalClient 全局 RAGFlow 客户端(单例,延迟初始化)
globalClient *Client
clientOnce sync.Once
)
// initClient 延迟初始化客户端
func initClient() {
clientOnce.Do(func() {
ctx := context.Background()
// 读取配置
baseURL, apiKey := loadConfig(ctx)
// 如果配置不完整,跳过初始化
if baseURL == "" || apiKey == "" {
g.Log().Warning(ctx, "⚠️ RAGFlow 配置未找到,请在项目 config.yml 中添加 ragflow.base_url 和 ragflow.api_key")
return
}
globalClient = &Client{
BaseURL: strings.TrimSuffix(baseURL, "/"),
APIKey: apiKey,
}
g.Log().Infof(ctx, "✅ RAGFlow 客户端初始化成功: baseURL=%s", baseURL)
})
}
// loadConfig 从配置文件加载 RAGFlow 配置
func loadConfig(ctx context.Context) (baseURL, apiKey string) {
baseURL = g.Cfg().MustGet(ctx, "ragflow.base_url", "").String()
apiKey = g.Cfg().MustGet(ctx, "ragflow.api_key", "").String()
return
}
// GetGlobalClient 获取全局客户端(延迟初始化)
func GetGlobalClient() *Client {
initClient()
return globalClient
}
// Client RAGFlow API 客户端
type Client struct {
BaseURL string
APIKey string
}
// CommonResponse 通用响应结构
type CommonResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
// IsSuccess 检查响应是否成功
func (r *CommonResponse) IsSuccess() bool {
return r.Code == 0
}
// request 发送 HTTP 请求(使用统一的common/http包)
func (c *Client) request(ctx context.Context, method, path string, body interface{}, result interface{}) (err error) {
fullURL := c.BaseURL + path
headers := map[string]string{
"Authorization": "Bearer " + c.APIKey,
"Content-Type": "application/json",
}
switch method {
case "GET":
err = commonHttp.Get(ctx, fullURL, headers, result, body)
case "POST":
err = commonHttp.Post(ctx, fullURL, headers, result, body)
case "PUT":
err = commonHttp.Put(ctx, fullURL, headers, result, body)
case "DELETE":
err = commonHttp.Delete(ctx, fullURL, headers, result, body)
default:
return gerror.Newf("unsupported method: %s", method)
}
if err != nil {
return gerror.Newf("RAGFlow API request failed: %v", err)
}
return
}
// buildQueryString 构建查询字符串
func buildQueryString(params map[string]interface{}) string {
if len(params) == 0 {
return ""
}
parts := make([]string, 0, len(params))
for k, v := range params {
parts = append(parts, url.QueryEscape(k)+"="+url.QueryEscape(g.NewVar(v).String()))
}
return strings.Join(parts, "&")
}