Home >Backend Development >Golang >Use go language to develop Baidu Translation API to realize mutual translation between Chinese and Indonesian

Use go language to develop Baidu Translation API to realize mutual translation between Chinese and Indonesian

WBOY
WBOYOriginal
2023-08-26 09:31:451463browse

Use go language to develop Baidu Translation API to realize mutual translation between Chinese and Indonesian

Using Go language to develop Baidu Translation API to realize mutual translation between Chinese and Indonesian

In the context of globalization, exchanges between countries have become more and more frequent. Translation has become an indispensable tool and plays an important role in cross-cultural communication. Baidu Translation API is a powerful and easy-to-use translation tool that can meet the translation needs between different languages. This article will introduce how to use Go language to develop Baidu Translation API to achieve mutual translation between Chinese and Indonesian, and attach corresponding code examples.

First, we need to register and create an application on the Baidu Translation Platform, and obtain the App ID and App Key of the application. The registration address is: https://fanyi-api.baidu.com/product/11

Next, we can write code in Go language and send translation requests to Baidu Translation API through HTTP requests. We can use Go's net/http package to send HTTP requests and the github.com/tidwall/gjson package to parse the returned JSON data.

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
    "strings"

    "github.com/tidwall/gjson"
)

const (
    appID  = "your_app_id"
    appKey = "your_app_key"
    apiURL = "https://fanyi-api.baidu.com/api/trans/vip/translate"
)

type TranslationResult struct {
    From        string `json:"from"`
    To          string `json:"to"`
    TransResult []struct {
        Src string `json:"src"`
        Dst string `json:"dst"`
    } `json:"trans_result"`
}

func main() {
    // 定义要翻译的文本和目标语言
    text := "Hello world!"
    targetLanguage := "id" // id表示印尼文

    // 构建请求参数
    values := url.Values{}
    values.Add("q", text)
    values.Add("from", "auto")
    values.Add("to", targetLanguage)
    values.Add("appid", appID)
    values.Add("salt", "1")
    values.Add("sign", generateSign(text))

    // 发送请求
    resp, err := http.PostForm(apiURL, values)
    if err != nil {
        fmt.Println("翻译请求发送失败:", err)
        return
    }
    defer resp.Body.Close()

    // 读取响应内容
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("响应内容读取失败:", err)
        return
    }

    // 解析JSON数据
    translationResult := TranslationResult{}
    err = json.Unmarshal(body, &translationResult)
    if err != nil {
        fmt.Println("JSON数据解析失败:", err)
        return
    }

    // 获取翻译结果
    if len(translationResult.TransResult) > 0 {
        fmt.Println("原文:", translationResult.TransResult[0].Src)
        fmt.Println("翻译结果:", translationResult.TransResult[0].Dst)
    } else {
        fmt.Println("翻译结果为空")
    }
}

// 生成签名
func generateSign(text string) string {
    return fmt.Sprintf("%x", md5.Sum([]byte(appID+text+"1"+appKey)))
}

In the above code, we first define a TranslationResult structure to store the returned translation results. Then, we define a main function in which we complete the following steps:

  1. Define the text to be translated and the target language.
  2. Construct request parameters, including text to be translated, source language, target language, application ID, random number and signature.
  3. Send HTTP request to obtain translation results.
  4. Parse the returned JSON data and obtain the translation results.
  5. Print the translation results.

It should be noted that in the generateSign function in the code, we use the md5 algorithm to encrypt the string to be signed. This is to ensure the security of the request. In actual development, we can also use other encryption algorithms to generate signatures.

Finally, we can run the code and see the translation results on the console. For example, if we translate "Hello world!" from English to Indonesian, we will get the translation result of "Halo dunia!".

Through the above code examples, we successfully developed a simple application using Go language to realize the mutual translation function between Chinese and Indonesian. With the powerful functions of Baidu Translation API, we can easily translate between different languages ​​and promote communication and cooperation between different countries and regions. I hope this article can help developers who are developing related applications.

The above is the detailed content of Use go language to develop Baidu Translation API to realize mutual translation between Chinese and Indonesian. 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