Go语言实战案例-项目实战篇:使用Go调用第三方API(如天气、翻译)

在现代应用开发中,调用第三方 API 是非常常见的场景,比如获取天气预报、翻译文本、发送短信等。Go 作为一门高效并发的编程语言,拥有强大的标准库和丰富的第三方库,可以非常方便地与外部 API 进行交互。本文将通过两个实战案例:天气查询接口翻译接口,带你掌握如何在 Go 中调用第三方 API。


一、准备工作

在开始之前,我们需要了解几个核心点:

  1. http 包 :Go 标准库提供的 net/http 是进行网络请求的核心工具。
  2. JSON 解析 :多数 API 返回 JSON 数据,可以使用 encoding/json 包进行解析。
  3. 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,涵盖了两类常见场景:

  1. 获取数据类 API(如天气查询)
  2. 功能性 API(如翻译文本)

核心步骤总结如下:

  • 使用 http 包发起请求;
  • 使用 encoding/json 解析返回结果;
  • 根据 API 要求添加必要的参数和签名。

通过这类实战,你可以很容易扩展到更多场景,例如调用短信网关、支付接口、图像识别等服务。


💡 思考练习: 试着扩展本文的示例,编写一个命令行工具,支持输入城市名称查询天气,或者输入一句话翻译成多国语言。

相关推荐
追逐时光者13 小时前
一套开源、美观、高性能的跨平台 .NET MAUI 控件库,助力轻松构建美观且功能丰富的应用程序!
后端·.net
码事漫谈13 小时前
重构的艺术:从‘屎山’恐惧到优雅掌控的理性之旅
后端
码事漫谈13 小时前
C++框架中基类修改导致兼容性问题的深度分析与总结
后端
华仔啊19 小时前
王者段位排行榜如何实现?Redis有序集合实战
java·redis·后端
豌豆花下猫19 小时前
Python 潮流周刊#120:新型 Python 类型检查器对比(摘要)
后端·python·ai
南方者20 小时前
当小学生的手写体也能识别出来,PP-OCRv5 稳了!
后端·图像识别
RoyLin21 小时前
TypeScript设计模式:解释器模式
前端·后端·typescript
易元21 小时前
模式组合应用-享元模式
后端·设计模式