之前使用python进行编程的时候,最常用的就是通过post和get一个URL抓取所需的数据,之前有一个短信接口使用的python实现的(post数据到某一网关URL),但由于python源码都是公开的(pyc也很容易就反编译出来),所以准备使用golang进行重写下,这样即使让其他人调用的话,也不会泄露网关的信息和调用方式 ,刚好也借此机会总结下golang下post和get数据的方法。

一、http get请求

由于get请求相对简单,这里先看下如果通过一个URL get数据:

/*
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下增加对应的头信息即可,如下:

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

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给网关数据时,刚开始一直不成功(也未报错),后来加上这一行后就成功发送信息了。

三、post bytes

上面直接post的是字符串,也可以post bytes数据给URL ,示例如下:

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 文件已给了我们很好的示例。

原文来自:http://www.361way.com/golang-post-get/5861.html

本文地址:https://www.linuxprobe.com/golang-post-get.html编辑:问题终结者,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/