Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > Go调用第三方API

使用Go调用第三方API的方法详解

作者:程序员爱钓鱼

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

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. 运行效果

城市:Beijing
温度:26.34℃
湿度:56%
天气:clear sky

三、案例2:调用翻译 API

1. 选择翻译 API

可以使用 百度翻译 API 或者 Google Translate 的开源接口。

2. 代码实现(以百度翻译为例)

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. 运行效果

翻译结果:Hello, world! -> 你好,世界!

四、总结

本文展示了如何在 Go 中调用第三方 API,涵盖了两类常见场景:

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

核心步骤总结如下:

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

到此这篇关于使用Go调用第三方API的方法详解的文章就介绍到这了,更多相关Go调用第三方API内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文