123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- package google
- import (
- "bytes"
- "encoding/json"
- "fmt"
- "html"
- "io/ioutil"
- "net/http"
- "strconv"
- )
- var (
- googleTranslateUrl = "http://8.210.169.38:8396/api/google/translate"
- )
- type GoogleApiResp struct {
- Code int `json:"code"`
- Msg string `json:"msg"`
- ErrMsg string `json:"err_msg"`
- Data GoogleApiRespData `json:"data"`
- }
- type GoogleApiRespData struct {
- ContentEn string `json:"content_en"`
- }
- // BatchTranslateHandlerByGoogle 批量google翻译
- func BatchTranslateHandlerByGoogle(contentMap map[string]string) (contentEnMap map[string]string, err error, errMsg string) {
- contentStr, _ := json.Marshal(contentMap)
- contentEnMap, err, errMsg = GoogleTranslateApi(string(contentStr))
- if err != nil {
- return
- }
- for k, v := range contentEnMap {
- v = html.UnescapeString(v)
- contentEnMap[k] = v
- }
- return
- }
- // GoogleTranslateApi content 为json字符串
- func GoogleTranslateApi(content string) (contentEnMap map[string]string, err error, errMsg string) {
- params := make(map[string]interface{})
- params["content"] = content
- bytesData, err := json.Marshal(params)
- if err != nil {
- err = fmt.Errorf("json.Marshal Err:" + err.Error())
- return
- }
- // 将解析之后的数据转为*Reader类型
- reader := bytes.NewReader(bytesData)
- resp, err := http.Post(googleTranslateUrl, "application/json", reader)
- if err != nil {
- errMsg = err.Error()
- err = fmt.Errorf("调用谷歌翻译接口失败")
- return
- }
- defer resp.Body.Close()
- if resp.StatusCode != 200 {
- err = fmt.Errorf("调用谷歌翻译接口失败")
- errMsg = "Status Code: " + strconv.Itoa(resp.StatusCode)
- return
- }
- body, _ := ioutil.ReadAll(resp.Body)
- //fmt.Println(string(body))
- var ret GoogleApiResp
- err = json.Unmarshal(body, &ret)
- if err != nil {
- errMsg = "解析谷歌翻译接口返回值失败 json.Unmarshal Err " + err.Error()
- err = fmt.Errorf("解析谷歌翻译接口返回值失败")
- return
- }
- if ret.Code != 200 {
- err = fmt.Errorf(ret.Msg)
- errMsg = ret.ErrMsg
- return
- }
- contentEnMap = make(map[string]string, 0)
- err = json.Unmarshal([]byte(ret.Data.ContentEn), &contentEnMap)
- if err != nil {
- errMsg = "解析谷歌翻译接口返回值失败2 json.Unmarshal Err " + err.Error()
- err = fmt.Errorf("解析谷歌翻译接口返回值失败")
- return
- }
- return
- }
|