This is a creation in Article, where the information may have evolved or changed.
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}