google_translate.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package google
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "eta_gn/eta_api/utils"
  6. "fmt"
  7. "html"
  8. "io/ioutil"
  9. "net/http"
  10. "strconv"
  11. )
  12. type GoogleApiResp struct {
  13. Code int `json:"code"`
  14. Msg string `json:"msg"`
  15. ErrMsg string `json:"err_msg"`
  16. Data GoogleApiRespData `json:"data"`
  17. }
  18. type GoogleApiRespData struct {
  19. ContentEn string `json:"content_en"`
  20. }
  21. // BatchTranslateHandlerByGoogle 批量google翻译
  22. func BatchTranslateHandlerByGoogle(contentMap map[string]string) (contentEnMap map[string]string, err error, errMsg string) {
  23. contentStr, _ := json.Marshal(contentMap)
  24. contentEnMap, err, errMsg = GoogleTranslateApi(string(contentStr))
  25. if err != nil {
  26. return
  27. }
  28. for k, v := range contentEnMap {
  29. v = html.UnescapeString(v)
  30. contentEnMap[k] = v
  31. }
  32. return
  33. }
  34. // GoogleTranslateApi content 为json字符串
  35. func GoogleTranslateApi(content string) (contentEnMap map[string]string, err error, errMsg string) {
  36. if utils.GoogleTranslateUrl == `` {
  37. //errMsg = "谷歌翻译服务未配置"
  38. //err = errors.New(errMsg)
  39. return
  40. }
  41. params := make(map[string]interface{})
  42. params["content"] = content
  43. bytesData, err := json.Marshal(params)
  44. if err != nil {
  45. err = fmt.Errorf("json.Marshal Err:" + err.Error())
  46. return
  47. }
  48. // 将解析之后的数据转为*Reader类型
  49. reader := bytes.NewReader(bytesData)
  50. resp, err := http.Post(utils.GoogleTranslateUrl, "application/json", reader)
  51. if err != nil {
  52. errMsg = err.Error()
  53. err = fmt.Errorf("调用谷歌翻译接口失败")
  54. return
  55. }
  56. defer resp.Body.Close()
  57. if resp.StatusCode != 200 {
  58. err = fmt.Errorf("调用谷歌翻译接口失败")
  59. errMsg = "Status Code: " + strconv.Itoa(resp.StatusCode)
  60. return
  61. }
  62. body, _ := ioutil.ReadAll(resp.Body)
  63. //fmt.Println(string(body))
  64. var ret GoogleApiResp
  65. err = json.Unmarshal(body, &ret)
  66. if err != nil {
  67. errMsg = "解析谷歌翻译接口返回值失败 json.Unmarshal Err " + err.Error()
  68. err = fmt.Errorf("解析谷歌翻译接口返回值失败")
  69. return
  70. }
  71. if ret.Code != 200 {
  72. err = fmt.Errorf(ret.Msg)
  73. errMsg = ret.ErrMsg
  74. return
  75. }
  76. contentEnMap = make(map[string]string, 0)
  77. err = json.Unmarshal([]byte(ret.Data.ContentEn), &contentEnMap)
  78. if err != nil {
  79. errMsg = "解析谷歌翻译接口返回值失败2 json.Unmarshal Err " + err.Error()
  80. err = fmt.Errorf("解析谷歌翻译接口返回值失败")
  81. return
  82. }
  83. return
  84. }