快速入门:使用 Go 通过文本翻译 API 获取受支持语言的列表Quickstart: Use the Translator Text API to get a list of supported languages using Go

本快速入门介绍如何使用 Go 和文本翻译 REST API 发出可以返回所支持语言的列表的 GET 请求。In this quickstart, you'll learn how to make a GET request that returns a list of supported languages using Go and the Translator Text REST API.

提示

如果你想一次看到所有代码,这个示例的源代码可以在 GitHub 上找到。If you'd like to see all the code at once, the source code for this sample is available on GitHub.

先决条件Prerequisites

本快速入门需要:This quickstart requires:

创建一个项目并导入必需的模块Create a project and import required modules

使用喜欢的 IDE 或编辑器创建新的 Go 项目,或在桌面上创建新的文件夹。Create a new Go project using your favorite IDE or editor or new folder on your desktop. 然后,将此代码片段复制到项目/文件夹的 get-languages.go 文件中。Then copy this code snippet into your project/folder in a file named get-languages.go.

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "net/url"
)

创建 main 函数Create the main function

让我们为应用程序创建 main 函数。Let's create the main function for our application. 你会注意到,它是单行代码。You'll notice it's a single line of code. 这是因为,我们要创建的单一函数用于为文本翻译获取和输出受支持语言的列表。That's because we're creating a single function to get and print the list of supported languages for Translator Text.

将以下代码复制到项目中:Copy this code into your project:

func main() {
    /*
     * This calls our getLanguages function, which we'll
     * create in the next section. It takes a single argument,
     * the subscription key.
     */
    getLanguages()
}

创建获取受支持语言列表的函数Create a function to get a list of supported languages

我们来创建获取受支持语言列表的函数。Let's create a function to get a list of supported languages.

func getLanguages() {
    /*  
     * In the next few sections, we'll add code to this
     * function to make a request and handle the response.
     */
}

接下来,构造 URL。Next, let's construct the URL. 使用 Parse()Query() 方法生成 URL。The URL is built using the Parse() and Query() methods.

将此代码复制到 getLanguages 函数中。Copy this code into the getLanguages function.

// Build the request URL. See: https://golang.org/pkg/net/url/#example_URL_Parse
u, _ := url.Parse("https://api.translator.azure.cn/languages")
q := u.Query()
q.Add("api-version", "3.0")
u.RawQuery = q.Encode()

备注

有关终结点、路由和请求参数的详细信息,请参阅文本翻译 API 3.0:语言For more information about endpoints, routes, and request parameters, see Translator Text API 3.0: Languages.

生成请求Build the request

将请求正文编码为 JSON 后,可以生成 POST 请求并调用文本翻译 API。Now that you've encoded the request body as JSON, you can build your POST request, and call the Translator Text API.

// Build the HTTP GET request
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
    log.Fatal(err)
}
// Add required headers
req.Header.Add("Content-Type", "application/json")

// Call the Translator Text API
res, err := http.DefaultClient.Do(req)
if err != nil {
    log.Fatal(err)
}

如果使用的是认知服务多服务订阅,则还必须在请求参数中包括 Ocp-Apim-Subscription-RegionIf you are using a Cognitive Services multi-service subscription, you must also include the Ocp-Apim-Subscription-Region in your request parameters. 详细了解如何使用多服务订阅进行身份验证Learn more about authenticating with the multi-service subscription.

处理并输出响应Handle and print the response

将此代码添加到 getLanguages 函数以解码 JSON 响应,然后格式化并输出结果。Add this code to the getLanguages function to decode the JSON response, and then format and print the result.

// Decode the JSON response
var result interface{}
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
    log.Fatal(err)
}
// Format and print the response to terminal
prettyJSON, _ := json.MarshalIndent(result, "", "  ")
fmt.Printf("%s\n", prettyJSON)

将其放在一起Put it all together

就是这样,你已构建了一个简单的程序。该程序可以调用文本翻译 API 并返回 JSON 响应。That's it, you've put together a simple program that will call the Translator Text API and return a JSON response. 现在,可以运行该程序了:Now it's time to run your program:

go run get-languages.go

如果希望将你的代码与我们的进行比较,请查看 GitHub 上提供的完整示例。If you'd like to compare your code against ours, the complete sample is available on GitHub.

示例响应Sample response

请在此语言列表中查找国家/地区缩写。Find the country/region abbreviation in this list of languages.

成功的响应以 JSON 格式返回,如以下示例所示:A successful response is returned in JSON as shown in the following example:

{
  "dictionary": {
    "af": {
      "name": "Afrikaans",
      "nativeName": "Afrikaans",
      "dir": "ltr",
      "translations": [
        {
          "name": "English",
          "nativeName": "English",
          "dir": "ltr",
          "code": "en"
        }
      ]
    },
    "ar": {
      "name": "Arabic",
      "nativeName": "العربية",
      "dir": "rtl",
      "translations": [
        {
          "name": "English",
          "nativeName": "English",
          "dir": "ltr",
          "code": "en"
        }
      ]
    },
...
  },
  "translation": {
    "af": {
      "name": "Afrikaans",
      "nativeName": "Afrikaans",
      "dir": "ltr"
    },
    "ar": {
      "name": "Arabic",
      "nativeName": "العربية",
      "dir": "rtl"
    },
...
  },
  "transliteration": {
    "ar": {
      "name": "Arabic",
      "nativeName": "العربية",
      "scripts": [
        {
          "code": "Arab",
          "name": "Arabic",
          "nativeName": "العربية",
          "dir": "rtl",
          "toScripts": [
            {
              "code": "Latn",
              "name": "Latin",
              "nativeName": "اللاتينية",
              "dir": "ltr"
            }
          ]
        },
        {
          "code": "Latn",
          "name": "Latin",
          "nativeName": "اللاتينية",
          "dir": "ltr",
          "toScripts": [
            {
              "code": "Arab",
              "name": "Arabic",
              "nativeName": "العربية",
              "dir": "rtl"
            }
          ]
        }
      ]
    },
...
  }
}

后续步骤Next steps

查看 API 参考,了解使用文本翻译 API 可以执行的所有操作。Take a look at the API reference to understand everything you can do with the Translator Text API.

另请参阅See also

了解如何使用文本翻译 API 执行以下操作:Learn how to use the Translator Text API to: