golang通过http访问外部网址

不同项目之前,通过http访问,进行数据沟通

先设定一个接口,确认外部能访问到

PHP写一个接口

php 复制代码
public function ceshi_return()
{
   $data = $this->request->param();
   $id = $data['id'];
   $res = Db::name('user')->field('id,status,price,name')->where(['id'=>$id])->find();
   $this->ajaxReturn($res);
}

返回效果:

get方式访问外部的接口

封装的函数

Go 复制代码
package utils
func GetRequest(url string) string {

	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Get(url)

	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	result, _ := ioutil.ReadAll(resp.Body)
	return string(result)
}

上层访问接口

因为要将请求到的数据,进行处理,所以需要提前定义一个结构体来接受处理这些数据

Go 复制代码
type GetData struct {
	Id     int    `json:"id"`
	Status int    `json:"status"`
	Price  int    `json:"price"`
	Name   string `json:"name"`
}


func GetUserData(c *gin.Context) {
	id := c.PostForm("id")
	url := "https://www.xxxx.com/admin/login/ceshi_return?id=" + id
	data := utils.GetRequest(url)

	d := []byte(data)
	var g GetData
	_ = json.Unmarshal(d, &g)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": g,
	})

}

效果

Post方式请求外部接口

封装函数

这里的访问方式,我写死了,设置成了json格式,有其他的方式,可以根据自己需求修改

Go 复制代码
package utils
func PostRequest(url string, data interface{}) string {

	client := &http.Client{Timeout: 5 * time.Second}
	jsonStr, _ := json.Marshal(data)
	resp, err := client.Post(url, "application/json", bytes.NewBuffer(jsonStr))
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	result, _ := ioutil.ReadAll(resp.Body)
	return string(result)
}

访问函数

Go 复制代码
//采用结构体的方式,来装要发送的数据
type PostData struct {
	Id int `json:"id"`
}

// 访问外部地址
func PostUserData(c *gin.Context) {
	id := c.PostForm("id")
	var p PostData
	p.Id, _ = strconv.Atoi(id)
	url := "https://www.xxxx.com/admin/login/ceshi_return"
	data := utils.PostRequest(url, p)
	fmt.Print(data)
	d := []byte(data)
	var g GetData
	_ = json.Unmarshal(d, &g)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": g,
	})

}

效果

相关推荐
@。12412 小时前
对于灰度发布(金丝雀发布)的了解
开发语言·前端
hsjkdhs13 小时前
C++之多层继承、多源继承、菱形继承
开发语言·c++·算法
Full Stack Developme13 小时前
Python Redis 教程
开发语言·redis·python
poemyang14 小时前
Goroutine间的“灵魂管道”:Channel如何实现数据同步与因果传递?
golang·并发编程
qq_49244844614 小时前
Jmeter设置负载阶梯式压测场景(详解教程)
开发语言·python·jmeter
FIavor.14 小时前
我发送给Apifox是http://localhost:9002/goods/getByUserName?name=张三 为什么会是500哪里错了?
java·服务器·网络协议·http
ID_1800790547314 小时前
京东获取整站实时商品详情数据|商品标题|数据分析提取教程
java·开发语言
Lazy龙15 小时前
Golang协程
golang
qiuiuiu41315 小时前
正点原子RK3568学习日志-编译第一个驱动程序helloworld
linux·c语言·开发语言·单片机
周之鸥15 小时前
从零部署 Astro 静态网站到云服务器(含 HTTPS 一键配置)
运维·服务器·ubuntu·http·https·astro