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

}

效果

相关推荐
大傻^7 分钟前
SpringAI2.0 Null Safety 实战:JSpecify 注解体系与 Kotlin 互操作
android·开发语言·人工智能·kotlin·springai
魑魅魍魉都是鬼21 分钟前
Java 适配器模式(Adapter Pattern)
java·开发语言·适配器模式
笨笨马甲22 分钟前
Qt MQTT
开发语言·qt
Fairy要carry41 分钟前
面试-Agent上下文过载、步骤混乱的问题
开发语言·python
程序员Ctrl喵1 小时前
异步编程:Event Loop 与 Isolate 的深层博弈
开发语言·flutter
liuyao_xianhui1 小时前
优选算法_两数之和_位运算_C++
java·开发语言·数据结构·c++·算法·链表·动态规划
童话ing1 小时前
【Golang】Golang Map数据结构底层原理
数据结构·golang·哈希算法
IT猿手1 小时前
MATLAB模拟四旋翼无人机飞行,机翼可独立旋转
开发语言·matlab·无人机
代龙涛1 小时前
WordPress 主题开发指南:模板文件、函数与页面选型规则
开发语言·后端·php·wordpress
代码探秘者1 小时前
【大模型应用】6.RAG 场景下的向量+关键词混合检索
java·开发语言·人工智能·python·spring