golang通過http訪問外部網(wǎng)址的操作方法
不同項(xiàng)目之前,通過http訪問,進(jìn)行數(shù)據(jù)溝通
先設(shè)定一個(gè)接口,確認(rèn)外部能訪問到
PHP寫一個(gè)接口
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方式訪問外部的接口
封裝的函數(shù)
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)
}上層訪問接口
因?yàn)橐獙⒄?qǐng)求到的數(shù)據(jù),進(jìn)行處理,所以需要提前定義一個(gè)結(jié)構(gòu)體來接受處理這些數(shù)據(jù)
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方式請(qǐng)求外部接口
封裝函數(shù)
這里的訪問方式,我寫死了,設(shè)置成了json格式,有其他的方式,可以根據(jù)自己需求修改
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)
}訪問函數(shù)
//采用結(jié)構(gòu)體的方式,來裝要發(fā)送的數(shù)據(jù)
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,
})
}效果

到此這篇關(guān)于golang通過http訪問外部網(wǎng)址的文章就介紹到這了,更多相關(guān)golang訪問外部網(wǎng)址內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Go-家庭收支記賬軟件項(xiàng)目實(shí)現(xiàn)
這篇文章主要介紹了Go-家庭收支記賬軟件項(xiàng)目實(shí)現(xiàn),本文章內(nèi)容詳細(xì),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,需要的朋友可以參考下2023-01-01
golang?pprof監(jiān)控memory?block?mutex統(tǒng)計(jì)原理分析
這篇文章主要為大家介紹了golang?pprof監(jiān)控memory?block?mutex統(tǒng)計(jì)原理分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
go mock server的簡易實(shí)現(xiàn)示例
這篇文章主要為大家介紹了go mock server的簡易實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
Go語言編程中判斷文件是否存在是創(chuàng)建目錄的方法
這篇文章主要介紹了Go語言編程中判斷文件是否存在是創(chuàng)建目錄的方法,示例都是使用os包下的函數(shù),需要的朋友可以參考下2015-10-10
使用Go中的Web3庫進(jìn)行區(qū)塊鏈開發(fā)的案例
區(qū)塊鏈作為一種分布式賬本技術(shù),在近年來取得了巨大的發(fā)展,而Golang作為一種高效、并發(fā)性強(qiáng)的編程語言,被廣泛用于區(qū)塊鏈開發(fā)中,本文將介紹如何使用Golang中的Web3庫進(jìn)行區(qū)塊鏈開發(fā),并提供一些實(shí)際案例,需要的朋友可以參考下2023-10-10

