最近做项目用到翻译功能,对接了一下科大讯飞的翻译api接口,demo如下:
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"strings"
)
const (
Host = "itrans.xf-yun.com"
Algorithm = "hmac-sha256"
HttpProto = "HTTP/1.1"
Uri = "/v1/its"
Url = "https://itrans.xf-yun.com/v1/its"
AppId = "your app_id"
AppSecret = "your app_secret"
AppKey = "your app_key"
Text = "今天天气怎么样" //需要翻译的文本
)
func main() {
client := &http.Client{}
//生成要访问的url
// 请求时间
currentTime := time.Now().UTC().Format(time.RFC1123)
// 生成签名
sign := generateSignature(Host, currentTime, "POST", Uri, HttpProto, AppSecret)
// 组装信息
authInfo := fmt.Sprintf(`api_key="%s",algorithm="%s",headers="host date request-line",signature="%s"`,AppKey, Algorithm, sign)
// 拼装请求body信息
requestParam := map[string]interface{}{
"header": map[string]interface{}{
"app_id": AppId,
"status": 3,
},
"parameter": map[string]interface{}{
"its": map[string]interface{}{
"from": "cn",
"to": "en",
"result": map[string]interface{}{},
},
},
"payload": map[string]interface{}{
"input_data": map[string]interface{}{
"encoding": "utf8",
"status": 3,
"text": base64.StdEncoding.EncodeToString([]byte(Text)),
},
},
}
// 请求信息
jsonByte, _ := json.Marshal(requestParam)
request, err := http.NewRequest("POST", Url, strings.NewReader(string(jsonByte)))
if err != nil {
panic(err)
}
q := request.URL.Query()
q.Add("host", Host)
q.Add("date", currentTime)
q.Add("authorization", base64.StdEncoding.EncodeToString([]byte(authInfo)))
request.URL.RawQuery = q.Encode()
request.Header.Set("content-type", "application/json")
//处理返回结果
response, _ := client.Do(request)
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
fmt.Println(string(body))
}
func generateSignature(host, date, httpMethod, requestUri, httpProto, secret string) string {
var signatureStr string
if len(host) != 0 {
signatureStr = "host: " + host + "\n"
}
signatureStr += "date: " + date + "\n"
signatureStr += httpMethod + " " + requestUri + " " + httpProto
return hmacsign(signatureStr, secret)
}
func hmacsign(data, secret string) string {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(data))
encodeData := mac.Sum(nil)
return base64.StdEncoding.EncodeToString(encodeData)
}
标签:map,string,demo,request,机器翻译,golang,host,signatureStr,interface
From: https://www.cnblogs.com/xingzr/p/17428016.html