当前位置: 代码网 > it编程>前端脚本>Golang > golang通过http访问外部网址的操作方法

golang通过http访问外部网址的操作方法

2024年05月20日 Golang 我要评论
不同项目之前,通过http访问,进行数据沟通先设定一个接口,确认外部能访问到php写一个接口public function ceshi_return(){ $data = $this->re

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

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

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方式访问外部的接口

封装的函数

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)
}

上层访问接口

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

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格式,有其他的方式,可以根据自己需求修改

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)
}

访问函数

//采用结构体的方式,来装要发送的数据
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,
	})
}

效果

到此这篇关于golang通过http访问外部网址的文章就介绍到这了,更多相关golang访问外部网址内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com