文章目录
- 一、官方地址
- 二、准备工作
- 三、代码示例
一、官方地址
https://learn.microsoft.com/zh-CN/azure/ai-services/translator/translator-text-apis?tabs=go
二、准备工作
创建服务
创建服务连接地址:https://portal.azure.com/#create/Microsoft.CognitiveServicesTextTranslation
根据自身需求创建
创建成功后找到密钥
三、代码示例
func Translation() {// 准备要翻译的文本textToTranslate := "Hello friend! What did you do today?"// 准备API请求的URLapiURL := "https://api.cognitive.microsofttranslator.com//translate?api-version=3.0&from=en&to=zh"// 准备API密钥apiKey := "<YOUR-TRANSLATOR-KEY>"// 准备API请求的bodyrequestBody, _ := json.Marshal([]map[string]string{{"Text": textToTranslate},})// 发起API请求req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(requestBody))req.Header.Set("Ocp-Apim-Subscription-Key", apiKey)req.Header.Set("Ocp-Apim-Subscription-Region", "<YOUR-RESOURCE-LOCATION>")req.Header.Set("Content-Type", "application/json")client := &http.Client{}resp, err := client.Do(req)if err != nil {logger.Errorf("Translation Error,errormsg:%s", err)}defer resp.Body.Close()// 读取API响应var result interface{}if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {logger.Errorf("Translation json.NewDecoder Error,errormsg:%s", err)}// 输出翻译结果prettyJSON, _ := json.MarshalIndent(result, "", " ")// 解析JSON数据if err := json.Unmarshal([]byte(prettyJSON), &translationResult); err != nil {logger.Errorf("Translation json.Unmarshal Error,errormsg:%s", err)}// 获取"text"字段的值text := translationResult[0].Translations[0].Text
}var translationResult []struct {Translations []struct {Text string `json:"text"`To string `json:"to"`} `json:"translations"`
}