文章目录
- 常见的天气 API 提供商有 OpenWeather,国内也有和风天气等。注册后即可获取 API Key。
- 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(“城市:%sn温度:%.2f℃n湿度:%d%%n天气:%sn”, weather.Name, weather.Main.Temp, weather.Main.Humidity, weather.Weather[0].Description) }
- 城市:Beijing 温度:26.34℃ 湿度:56% 天气:clear sky
- 可以使用 百度翻译 API 或者 Google Translate 的开源接口。
- 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 -> %sn”, result.TransResult[0].Src, result.TransResult[0].Dst) }
- 翻译结果:Hello, world! -> 你好,世界!
目录
- 引言
- 一、准备工作
- 二、案例1:调用天气查询 API
- 1. 注册并获取 API Key
- 2. 代码实现
- 3. 运行效果
- 三、案例2:调用翻译 API
- 1. 选择翻译 API
- 2. 代码实现(以百度翻译为例)
- 3. 运行效果
- 四、总结
在现代应用开发中,调用第三方 API 是非常常见的场景,比如获取天气预报、翻译文本、发送短信等。Go 作为一门高效并发的编程语言,拥有强大的标准库和丰富的第三方库,可以非常方便地与外部 API 进行交互。本文将通过两个实战案例:天气查询接口和翻译接口,带你掌握如何在 Go 中调用第三方 API。
在开始之前,我们需要了解几个核心点:
- http 包:Go 标准库提供的
net/http是进行网络请求的核心工具。 - JSON 解析:多数 API 返回 JSON 数据,可以使用
encoding/json包进行解析。 - API Key:部分第三方服务需要注册账号获取
API Key才能调用。
常见的天气 API 提供商有 OpenWeather,国内也有和风天气等。注册后即可获取 API Key。
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("城市:%sn温度:%.2f℃n湿度:%d%%n天气:%sn",
weather.Name,
weather.Main.Temp,
weather.Main.Humidity,
weather.Weather[0].Description)
}
城市:Beijing
温度:26.34℃
湿度:56%
天气:clear sky
可以使用 百度翻译 API 或者 Google Translate 的开源接口。
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 -> %sn", result.TransResult[0].Src, result.TransResult[0].Dst)
}
翻译结果:Hello, world! -> 你好,世界!
本文展示了如何在 Go 中调用第三方 API,涵盖了两类常见场景:
- 获取数据类 API(如天气查询)
- 功能性 API(如翻译文本)
核心步骤总结如下:
- 使用
http包发起请求; - 使用
encoding/json解析返回结果; - 根据 API 要求添加必要的参数和签名。
通过这类实战,你可以很容易扩展到更多场景,例如调用短信网关、支付接口、图像识别等服务。
到此这篇关于使用Go调用第三方API的方法详解的文章就介绍到这了,更多相关Go调用第三方API内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!
您可能感兴趣的文章:
- Go语言解决大模型API调用中的超时错误的方法
- Go语言调用DeepSeek API实现流式输出和对话
- Go语言调用ffmpeg-api实现音频重采样
- Go语言resty http包调用jenkins api实例
- django API 中接口的互相调用实例