google_translate.go 2.3 KB

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