Home  >  Article  >  Backend Development  >  Using go language to implement Baidu translation API for Chinese and English translation

Using go language to implement Baidu translation API for Chinese and English translation

WBOY
WBOYOriginal
2023-08-05 08:57:181345browse

Using Go language to implement Baidu Translation API for Chinese and English translation

1. Foreword

With the development of the Internet, communication between people has become more and more frequent, and the communication between people in different languages ​​has become more and more frequent. Communication problems among employees have also become increasingly prominent. To solve this problem, Baidu provides a powerful translation API that can achieve instant translation between Chinese and English. This article will introduce how to use Go language to call Baidu Translation API and give corresponding code examples.

2. Preparation

First, we need to create a translation API application on the Baidu Developer Platform and obtain the corresponding API Key and Secret Key. Create a config.json file in the project root directory to save this sensitive information.

{
  "APIKey": "your_api_key",
  "SecretKey": "your_secret_key"
}

3. Code implementation

First, we need to introduce the corresponding packages and tools.

package main

import (
    "crypto/md5"
    "encoding/hex"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
    "strings"
    "time"
)

Next, we need to implement a function to generate a signature. The specific generation rules are as follows:

  1. Sort the request parameters in alphabetical order by key.
  2. Splice the requested original string with the Secret Key and perform MD5 encryption.
  3. Convert the encrypted string to uppercase.

The following is the corresponding code implementation:

func generateSign(query string, salt string, secretKey string) string {
    h := md5.New()
    h.Write([]byte(secretKey + query + salt))
    sign := hex.EncodeToString(h.Sum(nil))
    return strings.ToUpper(sign)
}

Next, we need to implement a function to send HTTP requests and obtain the corresponding translation results.

func translate(query string, from string, to string) string {
    // 加载API Key和Secret Key
    configFile, err := ioutil.ReadFile("config.json")
    if err != nil {
        panic("Failed to read config file.")
    }

    var config struct {
        APIKey    string `json:"APIKey"`
        SecretKey string `json:"SecretKey"`
    }

    err = json.Unmarshal(configFile, &config)
    if err != nil {
        panic("Failed to parse config file.")
    }

    // 构造请求参数
    params := url.Values{}
    params.Set("q", query)
    params.Set("from", from)
    params.Set("to", to)
    params.Set("appid", config.APIKey)

    // 生成salt和sign
    salt := fmt.Sprintf("%d", time.Now().UnixNano())
    sign := generateSign(query, salt, config.SecretKey)

    // 构造请求URL
    apiURL := fmt.Sprintf("https://fanyi-api.baidu.com/api/trans/vip/translate?%s&salt=%s&sign=%s", params.Encode(), salt, sign)

    // 发送HTTP请求
    resp, err := http.Get(apiURL)
    if err != nil {
        panic("Failed to send request to Baidu Translate API.")
    }
    defer resp.Body.Close()

    // 解析响应体
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic("Failed to read response body.")
    }

    // 解析JSON数据
    var data struct {
        TransResult []struct {
            Src string `json:"src"`
            Dst string `json:"dst"`
        } `json:"trans_result"`
    }

    err = json.Unmarshal(body, &data)
    if err != nil {
        panic("Failed to parse response body.")
    }

    // 获取翻译结果
    translation := data.TransResult[0].Dst

    return translation
}

Finally, we need to implement a main function to test the translation function.

func main() {
    query := "Hello, World!"
    from := "auto"
    to := "zh"

    translation := translate(query, from, to)
    fmt.Println(translation)
}

4. Running results

Execute the following command in the terminal:

go run main.go

The program will call Baidu translation API to translate "Hello, World!" into Chinese, and then Print the results.

5. Summary

This article introduces in detail how to use Go language to implement Baidu Translation API for Chinese and English translation. By calling Baidu Translation API, we can easily achieve instant translation between different languages. I hope this article is helpful to you, thank you for reading!

The above is the detailed content of Using go language to implement Baidu translation API for Chinese and English translation. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn