google_translate.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. func BatchTranslateHandlerByGoogle(contentMap map[string]string) (contentEnMap map[string]string, err error, errMsg string) {
  22. contentStr, _ := json.Marshal(contentMap)
  23. contentEnMap, err, errMsg = GoogleTranslateApi(string(contentStr))
  24. if err != nil {
  25. return
  26. }
  27. for k, v := range contentEnMap {
  28. v = html.UnescapeString(v)
  29. contentEnMap[k] = v
  30. }
  31. return
  32. }
  33. func GoogleTranslateApi(content string) (contentEnMap map[string]string, err error, errMsg string) {
  34. if utils.GoogleTranslateUrl == `` {
  35. return
  36. }
  37. params := make(map[string]interface{})
  38. params["content"] = content
  39. bytesData, err := json.Marshal(params)
  40. if err != nil {
  41. err = fmt.Errorf("json.Marshal Err:" + err.Error())
  42. return
  43. }
  44. reader := bytes.NewReader(bytesData)
  45. resp, err := http.Post(utils.GoogleTranslateUrl, "application/json", reader)
  46. if err != nil {
  47. errMsg = err.Error()
  48. err = fmt.Errorf("调用谷歌翻译接口失败")
  49. return
  50. }
  51. defer resp.Body.Close()
  52. if resp.StatusCode != 200 {
  53. err = fmt.Errorf("调用谷歌翻译接口失败")
  54. errMsg = "Status Code: " + strconv.Itoa(resp.StatusCode)
  55. return
  56. }
  57. body, _ := ioutil.ReadAll(resp.Body)
  58. var ret GoogleApiResp
  59. err = json.Unmarshal(body, &ret)
  60. if err != nil {
  61. errMsg = "解析谷歌翻译接口返回值失败 json.Unmarshal Err " + err.Error()
  62. err = fmt.Errorf("解析谷歌翻译接口返回值失败")
  63. return
  64. }
  65. if ret.Code != 200 {
  66. err = fmt.Errorf(ret.Msg)
  67. errMsg = ret.ErrMsg
  68. return
  69. }
  70. contentEnMap = make(map[string]string, 0)
  71. err = json.Unmarshal([]byte(ret.Data.ContentEn), &contentEnMap)
  72. if err != nil {
  73. errMsg = "解析谷歌翻译接口返回值失败2 json.Unmarshal Err " + err.Error()
  74. err = fmt.Errorf("解析谷歌翻译接口返回值失败")
  75. return
  76. }
  77. return
  78. }