转:golang几种post方式


用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
}

via:http://studygolang.com/articles/4383

Archives