TranslateProp.go 2.62 KB
Newer Older
Ford committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
package service

import (
	"WorldEpcho/src/config"
	"bytes"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"log"
	"net/http"
)

// PropTranslateRequest 定义了发送给接口的请求体结构
type PropTranslateRequest1 struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Upset string `json:"upset"`
}

// PropTranslateResponse 定义了接口返回数据的结构
type PropTranslateResponse1 struct {
	Status  string `json:"status"`
	Content string `json:"content"`
}

// TranslateProp 发送翻译请求到服务器并处理返回的数据
func TranslateProp1(c *gin.Context) {
	// 判断用户是否登录
	if _, isLogin := IsUserLoggedIn(c); !isLogin {
		log.Println("用户未登录")
		c.JSON(http.StatusUnauthorized, gin.H{"code": 0, "message": "用户未登录"})
		return
	}

	name := c.PostForm("name")

	// 设置请求体中的固定值
	var requestBody PropTranslateRequest
	requestBody.ID = "96"
	requestBody.Upset = "mipm18vvi"
	requestBody.Name = name + "φ"

	// 读取请求中可能存在的其他数据
	/*	if err := c.BindJSON(&requestBody); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 0, "message": "无法解析请求体"})
		return
	}*/

	// 转换请求体为JSON
	requestBodyBytes, err := json.Marshal(requestBody)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 0, "message": "转换请求体为JSON出错"})
		return
	}

	// 从配置文件获取请求路径
	url := config.Conf.TranslatePropUrl

	// 发送POST请求
	response, err := http.Post(url, "application/json", bytes.NewBuffer(requestBodyBytes))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 0, "message": "发送请求出错"})
		return
	}
	defer response.Body.Close()

	// 读取返回的body内容
	responseBodyBytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 0, "message": "读取返回的body内容出错"})
		return
	}

	// 解析返回的JSON数据
	var translateResponse PropTranslateResponse
	if err := json.Unmarshal(responseBodyBytes, &translateResponse); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 0, "message": "解析返回的JSON数据出错"})
		return
	}

	// 记录翻译后的结果
	log.Printf(config.ColorPurple, "翻译结果: %+v\n", translateResponse, config.ColorReset)

	// 根据翻译结果的状态,向客户端发送不同的响应
	if translateResponse.Status == "OK" {
		c.JSON(http.StatusOK, gin.H{"code": 1, "message": "翻译成功", "translateResult": translateResponse})
	} else {
		c.JSON(http.StatusInternalServerError, gin.H{"code": 0, "message": "翻译服务返回错误"})
	}
}