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

2024-03-01 0 326
目录
  • get方式访问外部的接口
  • Post方式请求外部接口

不同项目之前,通过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);
}

返回效果:

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

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

效果

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

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通过http访问外部网址的文章就介绍到这了,更多相关golang访问外部网址内容请搜索悠久资源网以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠久资源网!

您可能感兴趣的文章:

  • Golang实现短网址/短链服务的开发笔记分享

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 Golang golang通过http访问外部网址的操作方法 https://www.u-9.cn/jiaoben/golang/178988.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务