码迷,mamicode.com
首页 > 其他好文 > 详细

golang几种post方式

时间:2015-06-24 20:32:39      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

用golang进行http请求类型多了,总结备忘一下。

 

1.普通的post\get请求

   var r http.Request
    r.ParseForm()
    r.Form.Add("uuid", orderUUID)
    bodystr := strings.TrimSpace(r.Form.Encode())
    request, err := http.NewRequest("GET", url, strings.NewReader(bodystr))
    if err != nil {
       //TODO:  
    }
    request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    request.Header.Set("Connection", "Keep-Alive")

    var resp *http.Response
    resp, err = http.DefaultClient.Do(request)
    if err != nil {
    //TODO:
    }

 

 

2. body全部二进制数据流进行post

//body提交二进制数据
func DoBytesPost(url string, data []byte) ([]byte, error) {

    body := bytes.NewReader(data)
    request, err := http.NewRequest(POST_METHOD, url, body)
    if err != nil {
        log.Println("http.NewRequest,[err=%s][url=%s]", err, url)
        return []byte(""), err
    }
    request.Header.Set("Connection", "Keep-Alive")
    var resp *http.Response
    resp, err = http.DefaultClient.Do(request)
    if err != nil {
        log.Println("http.Do failed,[err=%s][url=%s]", err, url)
        return []byte(""), err
    }
    defer resp.Body.Close()
    b, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Println("http.Do failed,[err=%s][url=%s]", err, url)
    }
    return b, err
}

 

 

3. 模拟web表单文件上传进行post

func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
    file, err := os.Open(path)
    if err != nil {
        return nil, err
    }
    defer file.Close()

    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)
    part, err := writer.CreateFormFile(paramName, path)
    if err != nil {
        return nil, err
    }
    _, err = io.Copy(part, file)

    for key, val := range params {
        _ = writer.WriteField(key, val)
    }
    err = writer.Close()
    if err != nil {
        return nil, err
    }
    request, err := http.NewRequest("POST", uri, body)
    request.Header.Set("Content-Type", writer.FormDataContentType())
    return request, err
}

 

golang几种post方式

标签:

原文地址:http://www.cnblogs.com/zhangqingping/p/4598337.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!