package google import ( "bytes" "encoding/json" "eta/eta_mobile/utils" "fmt" "html" "io/ioutil" "net/http" "strconv" ) 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) { if utils.GoogleTranslateUrl == `` { //errMsg = "谷歌翻译服务未配置" //err = errors.New(errMsg) return } 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(utils.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 }