gf框架 ghttp使用

案例中包含以下內(nèi)容

  • get請求
  • get請求攜帶參數(shù)
  • post請求攜帶參數(shù)
  • post請求發(fā)送xml數(shù)據(jù)
  • post請求發(fā)送單文件
  • post請求發(fā)送多文件
  • 自定義header
package main

import (
    "github.com/gogf/gf/frame/g"
    "github.com/gogf/gf/net/ghttp"
    "os"
    "path"
)
import "fmt"

func main() {
    //httpGet()
    //httpGetParam()
    //httpPost()
    //httpPost2(
    //httpPostXML()
    //httpSendFile()
    httpSendMultiFile()
}

// get請求
func httpGet(){
    if response, err := ghttp.Get("http://127.0.0.1:5000/get"); err != nil {
        panic(err)
    } else {
        defer response.Close()
        fmt.Println(response.ReadAllString())
    }
}

// get請求帶參數(shù)
func httpGetParam(){
    if response, err := ghttp.Get("http://127.0.0.1:5000/get?name=admin&age=21"); err != nil {
        panic(err)
    } else {
        defer response.Close()
        fmt.Println(response.ReadAllString())
    }
}

// post請求
func httpPost(){
    if response, err := ghttp.Post("http://127.0.0.1:5000/post", g.Map{"name": "admin"}); err != nil{
        panic(err)
    }else{
        defer response.Close()
        fmt.Println(response.ReadAllString())
    }
}

// post請求2
func httpPost2(){
    // 創(chuàng)建http客戶端對象
    c := ghttp.NewClient()
    // 默認請求頭為application/json
    // 設置請求頭為application/x-www-form-urlencoded
    c.SetHeader("Content-Type", "application/x-www-form-urlencoded")
    if response, err := c.Post("http://127.0.0.1:5000/post", `{"id": 1, "name": "admin"}`); err != nil{
        panic(err)
    }else{
        defer response.Close()
        fmt.Println(response.ReadAllString())
    }
}

// post發(fā)送xml請求
func httpPostXML(){
    c := ghttp.NewClient()
    c.SetHeader("Content-Type", "application/xml")

    xmlContent := `
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>`
    
    if response, err := c.Post("http://127.0.0.1:5000/data", xmlContent); err != nil {
        panic(err)
    } else {
        defer response.Close()
        fmt.Println( response.ReadAllString() )
    }
}

// post請求發(fā)送文件-單文件
func httpSendFile() {
    // 獲取當前文件夾
    filePath, err:= os.Getwd()
    if err != nil {
        panic(err)
    }

    // 拼接文件
    f := path.Join(filePath, "abc.txt")

    if response, err := ghttp.Post("http://127.0.0.1:5000/file", `upload_file1=@file:`+f); err != nil {
        panic(err)
    } else {
        defer response.Close()
        fmt.Println(response.ReadAllString())
    }
}

// post上傳多個文件
func httpSendMultiFile(){
    // 獲取當前文件夾
    filePath, err:= os.Getwd()
    if err != nil {
        panic(err)
    }

    // 拼接文件
    f1 := path.Join(filePath, "abc.txt")
    f2 := path.Join(filePath, "def.txt")

    if response, err := ghttp.Post("http://127.0.0.1:5000/file",
        fmt.Sprintf("file1=@file:%s&file2=@file:%s", f1, f2),
        ); err != nil {
        panic(err)
    } else {
        defer response.Close()
        fmt.Println(response.ReadAllString())
    }
}

Server端使用python flask框架

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/get')
def httpGet():
    print(request.headers)
    print('args->', request.args)
    return 'ok'

@app.route('/post', methods=['POST'])
def httpPost():
    print(request.headers)
    print('form->', request.form)
    return 'ok'

@app.route('/data', methods=['GET', 'POST'])
def httpData():
    print(request.headers)
    print('data->', request.data)
    return 'ok'

@app.route('/file', methods=['POST'])
def httpFile():
    print(request.headers)
    print('file', request.files)
    return 'ok'

@app.route('/to_struct', methods=['POST'])
def httpToStruct():
    return jsonify({'name': 'admin', 'age': 23})

if __name__ == '__main__':
    app.run(debug=True)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市笋除,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌慌洪,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,122評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件凑保,死亡現(xiàn)場離奇詭異,居然都是意外死亡涌攻,警方通過查閱死者的電腦和手機欧引,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來恳谎,“玉大人芝此,你說我怎么就攤上這事∫蛲矗” “怎么了婚苹?”我有些...
    開封第一講書人閱讀 164,491評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長鸵膏。 經(jīng)常有香客問我膊升,道長,這世上最難降的妖魔是什么谭企? 我笑而不...
    開封第一講書人閱讀 58,636評論 1 293
  • 正文 為了忘掉前任廓译,我火速辦了婚禮,結(jié)果婚禮上债查,老公的妹妹穿的比我還像新娘非区。我一直安慰自己,他們只是感情好盹廷,可當我...
    茶點故事閱讀 67,676評論 6 392
  • 文/花漫 我一把揭開白布征绸。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪管怠。 梳的紋絲不亂的頭發(fā)上剥汤,一...
    開封第一講書人閱讀 51,541評論 1 305
  • 那天,我揣著相機與錄音排惨,去河邊找鬼吭敢。 笑死,一個胖子當著我的面吹牛暮芭,可吹牛的內(nèi)容都是我干的鹿驼。 我是一名探鬼主播,決...
    沈念sama閱讀 40,292評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼辕宏,長吁一口氣:“原來是場噩夢啊……” “哼畜晰!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起瑞筐,我...
    開封第一講書人閱讀 39,211評論 0 276
  • 序言:老撾萬榮一對情侶失蹤凄鼻,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后聚假,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體块蚌,經(jīng)...
    沈念sama閱讀 45,655評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,846評論 3 336
  • 正文 我和宋清朗相戀三年膘格,在試婚紗的時候發(fā)現(xiàn)自己被綠了峭范。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,965評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡瘪贱,死狀恐怖纱控,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情菜秦,我是刑警寧澤甜害,帶...
    沈念sama閱讀 35,684評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站球昨,受9級特大地震影響尔店,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜褪尝,卻給世界環(huán)境...
    茶點故事閱讀 41,295評論 3 329
  • 文/蒙蒙 一闹获、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧河哑,春花似錦避诽、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,894評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽鲤妥。三九已至,卻和暖如春拱雏,著一層夾襖步出監(jiān)牢的瞬間棉安,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,012評論 1 269
  • 我被黑心中介騙來泰國打工铸抑, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留贡耽,地道東北人。 一個月前我還...
    沈念sama閱讀 48,126評論 3 370
  • 正文 我出身青樓鹊汛,卻偏偏與公主長得像蒲赂,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子刁憋,可洞房花燭夜當晚...
    茶點故事閱讀 44,914評論 2 355