golang下處理post和get數據的方法

以前使用python進行編程的時候,最經常使用的就是經過post和get一個URL抓取所需的數據,以前有一個短信接口使用的python實現的(post數據到某一網關URL),但因爲python源碼都是公開的(pyc也很容易就反編譯出來),因此準備使用golang進行重寫下,這樣即便讓其餘人調用的話,也不會泄露網關的信息和調用方式 ,恰好也藉此機會總結下golang下post和get數據的方法。php

1、http get請求html

因爲get請求相對簡單,這裏先看下若是經過一個URL get數據:python

/*
Http (curl) request in golang
@author www.361way.com <itybku@139.com>
*/
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
url := "https://361way.com/api/users"
req, _ := http.NewRequest("GET", url, nil)
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
}

如須要增長http header頭,只須要在req下增長對應的頭信息便可,以下:linux

req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("cache-control", "no-cache")
res, _ := http.DefaultClient.Do(req)

2、http post請求golang

http post請求代碼以下:編程

/*
Http (curl) request in golang
@author www.361way.com <itybku@139.com>
*/
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func main() {
url := "https://reqres.in/api/users"
payload := strings.NewReader("name=test&jab=teacher")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("content-type", "application/x-www-form-urlencoded")
req.Header.Add("cache-control", "no-cache")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
}

須要特別注意的是,上面的req.Header.Add  x-www-form-urlencoded 行是關鍵,必定不能取消,我在post給網關數據時,剛開始一直不成功(也未報錯),後來加上這一行後就成功發送信息了。api

3、post bytesapp

上面直接post的是字符串,也能夠post bytes數據給URL ,示例以下:curl

package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
func main() {
request_url := "http://localhost/index.php"
// 要 POST的 參數
form := url.Values{
"username": {"xiaoming"},
"address": {"beijing"},
"subject": {"Hello"},
"from": {"china"},
}
// func Post(url string, bodyType string, body io.Reader) (resp *Response, err error) {
//對form進行編碼
body := bytes.NewBufferString(form.Encode())
rsp, err := http.Post(request_url, "application/x-www-form-urlencoded", body)
if err != nil {
panic(err)
}
defer rsp.Body.Close()
body_byte, err := ioutil.ReadAll(rsp.Body)
if err != nil {
panic(err)
}
fmt.Println(string(body_byte))
}
一樣,涉及到http頭的時候,和上面同樣,經過下面的方式增長:

req, err := http.NewRequest("POST", hostURL, strings.NewReader(publicKey))
if err != nil {
glog.Fatal(err)
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

最後,推薦多看官方文檔,剛開始找了很多文檔一直不得要領,而官方request_test.go 文件已給了咱們很好的示例。post

原文來自: https://www.linuxprobe.com/golang-post-get.html

相關文章
相關標籤/搜索