golang post請(qǐng)求常用的幾種方式小結(jié)
更新時(shí)間:2021年04月27日 11:15:37 作者:誠(chéng)寜
這篇文章主要介紹了golang post請(qǐng)求常用的幾種方式小結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
post請(qǐng)求常用的幾種方式,記錄一下
func httpPost() {
resp, err := http.Post("https://www.abcd123.top/api/v1/login",
"application/x-www-form-urlencoded",
strings.NewReader("username=test&password=ab123123"))
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
func httpPostForm() {
resp, err := http.PostForm("https://www.denlery.top/api/v1/login",
url.Values{"username": {"auto"}, "password": {"auto123123"}})
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
func httpPostJson() {
jsonStr :=[]byte(`{ "username": "auto", "password": "auto123123" }`)
url:= "https://www.denlery.top/api/v1/login"
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
// handle error
}
defer resp.Body.Close()
statuscode := resp.StatusCode
hea := resp.Header
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
fmt.Println(statuscode)
fmt.Println(hea)
}
補(bǔ)充:golang中發(fā)送post的json請(qǐng)求
看代碼吧~
package main
import (
"encoding/json"
"log"
"net/http"
)
type test_struct struct {
Test string
}
//func test(rw http.ResponseWriter, req *http.Request) {
// req.ParseForm()
// log.Println(req.Form)
// //LOG: map[{"test": "that"}:[]]
// var t test_struct
// for key, _ := range req.Form {
// log.Println(key)
// //LOG: {"test": "that"}
// err := json.Unmarshal([]byte(key), &t)
// if err != nil {
// log.Println(err.Error())
// }
// }
// log.Println(t.Test)
// //LOG: that
//}
func test(rw http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var t test_struct
err := decoder.Decode(&t)
if err != nil {
panic(err)
}
log.Println(t.Test)
}
func main() {
http.HandleFunc("/test", test)
log.Fatal(http.ListenAndServe(":8082", nil))
}

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
Golang?手寫一個(gè)簡(jiǎn)單的并發(fā)任務(wù)?manager
這篇文章主要介紹了Golang?手寫一個(gè)簡(jiǎn)單的并發(fā)任務(wù)?manager,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08
Golang import本地包和導(dǎo)入問(wèn)題相關(guān)詳解
這篇文章主要介紹了Golang import本地包和導(dǎo)入問(wèn)題相關(guān)詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02
Golang基于JWT與Casbin身份驗(yàn)證授權(quán)實(shí)例詳解
這篇文章主要為大家介紹了Golang基于JWT與Casbin實(shí)現(xiàn)身份驗(yàn)證授權(quán)實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
使用go xorm來(lái)操作mysql的方法實(shí)例
今天小編就為大家分享一篇關(guān)于使用go xorm來(lái)操作mysql的方法實(shí)例,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-04-04

