在现代应用开发中,调用第三方 API 是非常常见的场景,比如获取天气预报、翻译文本、发送短信等。Go 作为一门高效并发的编程语言,拥有强大的标准库和丰富的第三方库,可以非常方便地与外部 API 进行交互。本文将通过两个实战案例:天气查询接口 和翻译接口,带你掌握如何在 Go 中调用第三方 API。
一、准备工作
在开始之前,我们需要了解几个核心点:
- http 包 :Go 标准库提供的
net/http
是进行网络请求的核心工具。 - JSON 解析 :多数 API 返回 JSON 数据,可以使用
encoding/json
包进行解析。 - API Key :部分第三方服务需要注册账号获取
API Key
才能调用。
二、案例1:调用天气查询 API
1. 注册并获取 API Key
常见的天气 API 提供商有 OpenWeather,国内也有和风天气等。注册后即可获取 API Key
。
2. 代码实现
go
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
const apiKey = "your_api_key"
const city = "Beijing"
type WeatherResponse struct {
Name string `json:"name"`
Main struct {
Temp float64 `json:"temp"`
Humidity int `json:"humidity"`
} `json:"main"`
Weather []struct {
Description string `json:"description"`
} `json:"weather"`
}
func main() {
url := fmt.Sprintf("https://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=metric", city, apiKey)
resp, err := http.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var weather WeatherResponse
if err := json.Unmarshal(body, &weather); err != nil {
panic(err)
}
fmt.Printf("城市:%s\n温度:%.2f℃\n湿度:%d%%\n天气:%s\n",
weather.Name,
weather.Main.Temp,
weather.Main.Humidity,
weather.Weather[0].Description)
}
3. 运行效果
arduino
城市:Beijing
温度:26.34℃
湿度:56%
天气:clear sky
三、案例2:调用翻译 API
1. 选择翻译 API
可以使用 百度翻译 API 或者 Google Translate 的开源接口。
2. 代码实现(以百度翻译为例)
go
package main
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
)
const appID = "your_app_id"
const appKey = "your_secret_key"
type TranslateResponse struct {
From string `json:"from"`
To string `json:"to"`
TransResult []struct {
Src string `json:"src"`
Dst string `json:"dst"`
} `json:"trans_result"`
}
func makeSign(query string, salt string) string {
signStr := appID + query + salt + appKey
hash := md5.Sum([]byte(signStr))
return hex.EncodeToString(hash[:])
}
func main() {
query := "Hello, world!"
salt := fmt.Sprintf("%d", time.Now().Unix())
sign := makeSign(query, salt)
params := url.Values{}
params.Set("q", query)
params.Set("from", "en")
params.Set("to", "zh")
params.Set("appid", appID)
params.Set("salt", salt)
params.Set("sign", sign)
resp, err := http.Post("https://fanyi-api.baidu.com/api/trans/vip/translate",
"application/x-www-form-urlencoded",
strings.NewReader(params.Encode()))
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var result TranslateResponse
if err := json.Unmarshal(body, &result); err != nil {
panic(err)
}
fmt.Printf("翻译结果:%s -> %s\n", result.TransResult[0].Src, result.TransResult[0].Dst)
}
3. 运行效果
rust
翻译结果:Hello, world! -> 你好,世界!
四、总结
本文展示了如何在 Go 中调用第三方 API,涵盖了两类常见场景:
- 获取数据类 API(如天气查询)
- 功能性 API(如翻译文本)
核心步骤总结如下:
- 使用
http
包发起请求; - 使用
encoding/json
解析返回结果; - 根据 API 要求添加必要的参数和签名。
通过这类实战,你可以很容易扩展到更多场景,例如调用短信网关、支付接口、图像识别等服务。
💡 思考练习: 试着扩展本文的示例,编写一个命令行工具,支持输入城市名称查询天气,或者输入一句话翻译成多国语言。