google_translate.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package controller
  2. import (
  3. "encoding/json"
  4. "github.com/gin-gonic/gin"
  5. "github.com/go-playground/validator/v10"
  6. "hongze/hongze_google_api/controller/resp"
  7. "hongze/hongze_google_api/global"
  8. "hongze/hongze_google_api/models"
  9. "hongze/hongze_google_api/services"
  10. )
  11. type GoogleTranslateController struct{}
  12. func (er *GoogleTranslateController) Translate(c *gin.Context) {
  13. var req models.GoogleTranslateReq
  14. err := c.ShouldBind(&req)
  15. if err != nil {
  16. errs, ok := err.(validator.ValidationErrors)
  17. if !ok {
  18. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  19. return
  20. }
  21. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  22. return
  23. }
  24. contentMap := make(map[string]string)
  25. err = json.Unmarshal([]byte(req.Content), &contentMap)
  26. if err != nil {
  27. resp.FailMsg("待翻译的内容解析成json失败", "失败,Err:"+err.Error(), c)
  28. return
  29. }
  30. contentEnMap, err := services.BatchTranslateHandlerByGoogle(contentMap)
  31. if err != nil {
  32. resp.FailMsg("翻译失败", "翻译失败,Err:"+err.Error(), c)
  33. return
  34. }
  35. bytes, err := json.Marshal(contentEnMap)
  36. if err != nil {
  37. resp.FailMsg("翻译失败", "翻译失败,json.Marshal Err:"+err.Error(), c)
  38. return
  39. }
  40. contentEnStr := string(bytes)
  41. baseData := new(models.GoogleTranslateResp)
  42. baseData.ContentEn = contentEnStr
  43. resp.OkData("操作成功", baseData, c)
  44. }
  45. func (er *GoogleTranslateController) SingleTranslate(c *gin.Context) {
  46. var req models.GoogleTranslateReq
  47. err := c.ShouldBind(&req)
  48. if err != nil {
  49. errs, ok := err.(validator.ValidationErrors)
  50. if !ok {
  51. resp.FailData("参数解析失败", "Err:"+err.Error(), c)
  52. return
  53. }
  54. resp.FailData("参数解析失败", errs.Translate(global.Trans), c)
  55. return
  56. }
  57. if req.Content == "" {
  58. resp.FailMsg("请输入要翻译的内容", "请输入要翻译的内容", c)
  59. return
  60. }
  61. contentEnStr, err := services.SingleTranslateHandlerByGoogle(req.Content)
  62. if err != nil {
  63. resp.FailMsg("翻译失败", "翻译失败,Err:"+err.Error(), c)
  64. return
  65. }
  66. baseData := new(models.GoogleTranslateResp)
  67. baseData.ContentEn = contentEnStr
  68. resp.OkData("操作成功", baseData, c)
  69. }