使用Go調(diào)用第三方API的方法詳解
引言
在現(xiàn)代應(yīng)用開發(fā)中,調(diào)用第三方 API 是非常常見的場(chǎng)景,比如獲取天氣預(yù)報(bào)、翻譯文本、發(fā)送短信等。Go 作為一門高效并發(fā)的編程語(yǔ)言,擁有強(qiáng)大的標(biāo)準(zhǔn)庫(kù)和豐富的第三方庫(kù),可以非常方便地與外部 API 進(jìn)行交互。本文將通過(guò)兩個(gè)實(shí)戰(zhàn)案例:天氣查詢接口和翻譯接口,帶你掌握如何在 Go 中調(diào)用第三方 API。
一、準(zhǔn)備工作
在開始之前,我們需要了解幾個(gè)核心點(diǎn):
- http 包:Go 標(biāo)準(zhǔn)庫(kù)提供的
net/http是進(jìn)行網(wǎng)絡(luò)請(qǐng)求的核心工具。 - JSON 解析:多數(shù) API 返回 JSON 數(shù)據(jù),可以使用
encoding/json包進(jìn)行解析。 - API Key:部分第三方服務(wù)需要注冊(cè)賬號(hào)獲取
API Key才能調(diào)用。
二、案例1:調(diào)用天氣查詢 API
1. 注冊(cè)并獲取 API Key
常見的天氣 API 提供商有 OpenWeather,國(guó)內(nèi)也有和風(fēng)天氣等。注冊(cè)后即可獲取 API Key。
2. 代碼實(shí)現(xiàn)
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. 運(yùn)行效果
城市:Beijing 溫度:26.34℃ 濕度:56% 天氣:clear sky
三、案例2:調(diào)用翻譯 API
1. 選擇翻譯 API
可以使用 百度翻譯 API 或者 Google Translate 的開源接口。
2. 代碼實(shí)現(xiàn)(以百度翻譯為例)
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("翻譯結(jié)果:%s -> %s\n", result.TransResult[0].Src, result.TransResult[0].Dst)
}
3. 運(yùn)行效果
翻譯結(jié)果:Hello, world! -> 你好,世界!
四、總結(jié)
本文展示了如何在 Go 中調(diào)用第三方 API,涵蓋了兩類常見場(chǎng)景:
- 獲取數(shù)據(jù)類 API(如天氣查詢)
- 功能性 API(如翻譯文本)
核心步驟總結(jié)如下:
- 使用
http包發(fā)起請(qǐng)求; - 使用
encoding/json解析返回結(jié)果; - 根據(jù) API 要求添加必要的參數(shù)和簽名。
通過(guò)這類實(shí)戰(zhàn),你可以很容易擴(kuò)展到更多場(chǎng)景,例如調(diào)用短信網(wǎng)關(guān)、支付接口、圖像識(shí)別等服務(wù)。
到此這篇關(guān)于使用Go調(diào)用第三方API的方法詳解的文章就介紹到這了,更多相關(guān)Go調(diào)用第三方API內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解Go語(yǔ)言中如何創(chuàng)建Cron定時(shí)任務(wù)
Cron是一個(gè)強(qiáng)大的定時(shí)任務(wù)調(diào)度庫(kù),它允許開發(fā)者在Go應(yīng)用中方便地設(shè)置和管理定時(shí)任務(wù),本文將結(jié)合具體案例,詳細(xì)介紹Cron在Go語(yǔ)言中的用法,需要的可以參考下2024-10-10
Golang 標(biāo)準(zhǔn)庫(kù) tips之waitgroup詳解
本篇文章給大家介紹Golang 標(biāo)準(zhǔn)庫(kù) tips之waitgroup的相關(guān)知識(shí),包括使用 channel 實(shí)現(xiàn) WaitGroup 的功能介紹,感興趣的朋友跟隨小編一起看看吧2021-07-07
基于Golang實(shí)現(xiàn)Redis協(xié)議解析器
這篇文章主要為大家詳細(xì)介紹了如何通過(guò)GO語(yǔ)言編寫簡(jiǎn)單的Redis協(xié)議解析器,文中的示例代碼講解詳細(xì),對(duì)我們深入了解Go語(yǔ)言有一定的幫助,需要的可以參考一下2023-03-03

