不同项目之前,通过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访问外部网址内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论