Golang several post modes

Source: Internet
Author: User

With Golang HTTP request type is much, summary of the memo.

1. Common Post\get Requests

varr http. Request R.parseform () r.form.add ( "UUID", orderuuid) Bodystr: = Strings. Trimspace (R.form.encode ()) request, Err: = http. Newrequest ("GET", URL, strings. Newreader (BODYSTR))ifErr! =Nil {//todo:} request. Header.set ("Content-type","application/x-www-form-urlencoded") Request. Header.set ("Connection","keep-alive")    varRESP *http. Response resp, err=http. Defaultclient.do (Request)ifErr! =Nil {//todo:    }

2. Body all binary data stream for post

//body commits binary dataFunc dobytespost (URLstring, data []byte) ([]byte, error) { body: = bytes. Newreader (data) request, err:=http. Newrequest (post_method, url, body)ifErr! =Nil {log. Println ("http. newrequest,[err=%s][url=%s]", err, URL)return[]byte(""), err}Request. Header.set ("Connection","keep-alive")    varRESP *http. Response resp, err=http. Defaultclient.do (Request)ifErr! =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)ifErr! =Nil {log. Println ("http. Do failed,[err=%s][url=%s]", err, URL)} returnB, err}

3. Simulate Web Form file upload for post

Func newfileuploadrequest (URIstring,paramsmap[string]string, ParamName, Pathstring) (*http. Request, error) {file, err:=OS. Open (PATH)ifErr! =Nil {returnNil, 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) forKey, Val: = Rangeparams {        _ =writer. Writefield (Key, Val)} Err=writer. Close ()ifErr! =Nil {returnnil, err} request, err:= http. Newrequest ("POST", URI, body) request. Header.set ("Content-type", writer. Formdatacontenttype ())returnrequest, err}

Golang several post modes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.