golang下处理post和get数据的方法

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

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

转载于:https://my.oschina.net/ssdlinux/blog/2964281

评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符 “速评一下”
<div class="post-text" itemprop="text"> <p>I'm kinda new in Go, so, sorry if this is a silly question.</p> <p>I have been recently trying some API with Echo. I'm trying to test a route(POST) handler of Go echo that gets a json and puts it in an array. Bellow is the code for the handler <strong>main.go</strong> and for the test <strong>test_main.go</strong></p> <p><code>main.go</code></p> <pre><code>type Houses struct { Name string `json:"name,ommitempty"` Address string `json:"address,omitempty"` } var houses []Houses func newHouse(c echo.Context) error { m := echo.Map{} if err := c.Bind(&m); err != nil { return err } dv := Houses{ Name: m["name"].(string), Address: m["address"].(string), } houses = append(houses, dv) js, _ := json.Marshal(houses) fmt.Println(fmt.Sprintf("%s", js)) return c.JSON(http.StatusOK, string(js)) } </code></pre> <p><code>test_main.go</code></p> <pre><code>import ( "net/http" "net/http/httptest" "strings" "testing" "github.com/labstack/echo" "github.com/stretchr/testify/assert" ) var userJSON = `{"name":"Jhon Doe","address":"High St."}` func TestModel(t *testing.T) { url := "/new_house" e := echo.New() req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(userJSON)) req.Header.Set("Content-Type", "application/json") if err != nil { t.Errorf("The request could not be created because of: %v", err) } rec := httptest.NewRecorder() c := e.NewContext(req, rec) // c.SetPath("/new_house") // c.JSON(http.StatusOK, Devices{"Jhon Doe", "Middle Way"}) res := rec.Result() defer res.Body.Close() if assert.NoError(t, newHouse(c)) { assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, "["+userJSON+"]", rec.Body.String()) } } </code></pre> <p>The test fails with the error shown bellow even though the handler works properly if called by curl. </p> <pre><code>[{"name":"Jhon Doe","address":"High St."}] --- FAIL: TestModel (0.00s) /home/gaidaros/Code/echo-badger/models/model_test.go:34: Error Trace: model_test.go:34 Error: Not equal: expected: "[{\"name\":\"Jhon Doe\",\"address\":\"High St.\"}]" actual : "\"[{\\\"name\\\":\\\"Jhon Doe\\\",\\\"address\\\":\\\"High St.\\\"}]\"" Diff: --- Expected +++ Actual @@ -1 +1 @@ -[{"name":"Jhon Doe","address":"High St."}] +"[{\"name\":\"Jhon Doe\",\"address\":\"High St.\"}]" Test: TestModel FAIL exit status 1 </code></pre> <p>After several days of struggling over it I couldn't figure out how to make the actual output to match the expected, so I'm posting here in hopes of getting past this obstacle. Any help is appreciated!</p> </div>
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页