golang编程入门之http请求天气实例
作者:embedsky 时间:2024-05-09 09:32:00
golang学习第一波,使用http get请求高德天气接口。
一、准备内容:
1、注册高德开发者账号,申请key
2、golang开发工具LiteIDE(可自行百度)。
或者https://www.aspxhome.com/softjc/119086.html
3、大致了解下golang基础语法。
二、直接上代码
因为代码注释非常详尽,故直接上代码。
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
rlt, err := doHttpGetRequest("https://restapi.amap.com/v3/weather/weatherInfo?key=你的高德key&city=110101")
if err != nil {
fmt.Println("net req error")
} else {
fmt.Println(rlt)
}
}
// 自定义http get请求函数
// 入参:请求url
// 返回值:rlt,天气数据。err,错误信息
// 网络请求
func doHttpGetRequest(url string) (rlt string, err error) {
// http.Get在net/http中,所以要import "net/http"
resp, err := http.Get(url)
if err != nil {
return "", err
} else {
// 使用efer resp.Body.Close()。当doHttpGetRequest成功return之后,执行此行语句。多用于句柄关闭
defer resp.Body.Close()
// io流数据读取。需要引用io/ioutil
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
} else {
return string(body), err
}
}
}
注:我的高德key:d2315f3b0b4e57bbf5428e755a73e692。供测试使用
返回结果:
测试结果
来源:https://www.jianshu.com/p/0861f57f5dd1
标签:golang,http,请求天气
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python引入导入自定义模块和外部文件的实例
2023-01-25 10:02:18
python中的json数据和pyecharts模块入门示例教程
2023-02-22 04:58:37
![](https://img.aspxhome.com/file/2023/9/87659_0s.jpg)
Python Multiprocessing多进程 使用tqdm显示进度条的实现
2021-04-03 19:15:08
![](https://img.aspxhome.com/file/2023/0/118570_0s.png)
如何使用PHP中的字符串函数
2024-05-11 10:01:59
python中关于eval函数的使用及说明
2023-03-02 14:28:35
javascript中select下拉框的用法总结
2024-04-19 09:57:51
![](https://img.aspxhome.com/file/2023/2/135992_0s.png)
mysql mysqldump只导出表结构或只导出数据的实现方法
2024-01-23 19:46:55
python实现linux下使用xcopy的方法
2022-08-16 07:52:09
简单了解Python多态与属性运行原理
2021-03-13 21:29:42
Python中scatter函数参数及用法详解
2022-05-03 09:55:58
![](https://img.aspxhome.com/file/2023/9/97649_0s.jpg)
Python+OpenCV实现单个圆形孔和针检测
2023-05-04 10:38:11
![](https://img.aspxhome.com/file/2023/0/124160_0s.jpg)
Python数字图像处理代数之加减乘运算
2023-03-20 07:51:26
![](https://img.aspxhome.com/file/2023/7/82667_0s.png)
SQL“多字段模糊匹配关键字查询”
2008-04-24 14:16:00
MYSQL每隔10分钟进行分组统计的实现方法
2024-01-22 13:56:42
go 对象池化组件 bytebufferpool使用详解
2024-02-10 14:26:11
Python制作简易注册登录系统
2022-08-25 14:46:28
![](https://img.aspxhome.com/file/2023/7/68327_0s.jpg)
利用Django提供的ModelForm增删改数据的方法
2021-02-04 04:13:00
最新MySQL高级SQL语句大全
2024-01-24 22:58:00
![](https://img.aspxhome.com/file/2023/8/72448_0s.png)
python函数默认参数使用避坑指南
2023-06-19 13:37:50
![](https://img.aspxhome.com/file/2023/6/90296_0s.png)
Python使用pyyaml模块处理yaml数据
2023-11-29 10:08:39