sdk_generate/internal/handler/file_content.go

103 lines
2.6 KiB
Go

package handler
import (
"bytes"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"time"
)
// ConvertResponse 定义接口响应结构
type ConvertResponse struct {
Filename string `json:"filename"`
LlmUsed bool `json:"llm_used"`
Markdown string `json:"markdown"`
Size int `json:"size"`
Success bool `json:"success"`
Title *string `json:"title"`
}
// ConvertRequest 定义请求参数结构
type ConvertRequest struct {
File multipart.File
FileName string
LlmModel string
LlmApiKey string
LlmBaseUrl string
LlmPrompt string
}
const url = "http://121.199.38.107:5001/convert"
// ConvertFile 调用 /convert 接口识别本地文件内容
func ConvertFile(req ConvertRequest) (*ConvertResponse, error) {
defer req.File.Close()
// 创建 multipart 表单
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// 添加文件字段
part, err := writer.CreateFormFile("file", req.FileName)
if err != nil {
return nil, fmt.Errorf("创建文件表单字段失败: %w", err)
}
if _, err := io.Copy(part, req.File); err != nil {
return nil, fmt.Errorf("复制文件内容失败: %w", err)
}
// 添加可选参数(如果提供)
if req.LlmModel != "" {
_ = writer.WriteField("llm_model", req.LlmModel)
}
if req.LlmApiKey != "" {
_ = writer.WriteField("llm_api_key", req.LlmApiKey)
}
if req.LlmBaseUrl != "" {
_ = writer.WriteField("llm_base_url", req.LlmBaseUrl)
}
if req.LlmPrompt != "" {
_ = writer.WriteField("llm_prompt", req.LlmPrompt)
}
// 关闭 multipart writer
if err = writer.Close(); err != nil {
return nil, fmt.Errorf("关闭表单写入器失败: %w", err)
}
// 创建 HTTP 请求
httpReq, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, fmt.Errorf("创建HTTP请求失败: %w", err)
}
httpReq.Header.Set("Content-Type", writer.FormDataContentType())
// 发送请求
client := &http.Client{Timeout: 60 * time.Second}
resp, err := client.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("发送请求失败: %w", err)
}
defer resp.Body.Close()
// 读取响应
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("读取响应失败: %w", err)
}
// 检查 HTTP 状态码
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("请求返回非200状态码: %d, 响应: %s", resp.StatusCode, string(respBody))
}
// 解析响应 JSON
var result ConvertResponse
if err := json.Unmarshal(respBody, &result); err != nil {
return nil, fmt.Errorf("解析响应JSON失败: %w, 原始响应: %s", err, string(respBody))
}
return &result, nil
}