本文整理匯總了Golang中http.Request.Body方法的典型用法代碼示例。如果您正苦於以下問題:Golang Request.Body方法的具體用法?Golang Request.Body怎麽用?Golang Request.Body使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類http.Request
的用法示例。
在下文中一共展示了Request.Body方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: RoundTrip
func (t *logTransport) RoundTrip(req *http.Request) (*http.Response, os.Error) {
var buf bytes.Buffer
os.Stdout.Write([]byte("\n[request]\n"))
if req.Body != nil {
req.Body = ioutil.NopCloser(&readButCopy{req.Body, &buf})
}
req.Write(os.Stdout)
if req.Body != nil {
req.Body = ioutil.NopCloser(&buf)
}
os.Stdout.Write([]byte("\n[/request]\n"))
res, err := t.rt.RoundTrip(req)
fmt.Printf("[response]\n")
if err != nil {
fmt.Printf("ERROR: %v", err)
} else {
body := res.Body
res.Body = nil
res.Write(os.Stdout)
if body != nil {
res.Body = ioutil.NopCloser(&echoAsRead{body})
}
}
return res, err
}
示例2: authPut
// Put issues a PUT to the specified URL.
//
// Caller should close r.Body when done reading it.
func authPut(url, user, pwd, client, clientURL, version, agent, bodyType string,
body io.Reader) (r *http.Response, err os.Error) {
var req http.Request
req.Method = "PUT"
req.Body = body.(io.ReadCloser)
if user != "" && pwd != "" {
req.Header = map[string][]string{
"Content-Type": {bodyType},
"Transfer-Encoding": {"chunked"},
"User-Agent": {agent},
"X-FluidDB-Client": {client},
"X-FluidDB-Client-URL": {clientURL},
"X-FluidDB-Version": {version},
"Authorization": {"Basic " + encodedUsernameAndPassword(user, pwd)},
}
} else {
req.Header = map[string][]string{
"Content-Type": {bodyType},
"Transfer-Encoding": {"chunked"},
"User-Agent": {agent},
"X-FluidDB-Client": {client},
"X-FluidDB-Client-URL": {clientURL},
"X-FluidDB-Version": {version},
}
}
req.URL, err = http.ParseURL(url)
if err != nil {
return nil, err
}
return send(&req)
}
示例3: NewRequest
func NewRequest(method string, url string, doc IDocument) *http.Request {
var req http.Request
req.Method = method
req.ProtoMajor = 1
req.ProtoMinor = 1
req.Close = true
req.Header = map[string]string{
"Content-Type": "application/json",
"X-Riak-ClientId": "riak.go",
}
if doc.VectorClock() != "" {
req.Header["X-Riak-Vclock"] = doc.VectorClock()
}
req.TransferEncoding = []string{"chunked"}
req.URL, _ = http.ParseURL(url)
if doc.Json() != "" {
cb := &ClosingBuffer{bytes.NewBufferString(doc.Json())}
var rc io.ReadCloser
rc = cb
req.Body = rc
}
fmt.Println(req.URL)
return &req
}
示例4: connect
func (conn *streamConn) connect() (*http.Response, os.Error) {
if conn.stale {
return nil, os.NewError("Stale connection")
}
tcpConn, err := net.Dial("tcp", "", conn.url.Host+":80")
if err != nil {
return nil, err
}
conn.clientConn = http.NewClientConn(tcpConn, nil)
var req http.Request
req.URL = conn.url
req.Method = "GET"
req.Header = map[string]string{}
req.Header["Authorization"] = "Basic " + conn.authData
if conn.postData != "" {
req.Method = "POST"
req.Body = nopCloser{bytes.NewBufferString(conn.postData)}
req.ContentLength = int64(len(conn.postData))
req.Header["Content-Type"] = "application/x-www-form-urlencoded"
}
err = conn.clientConn.Write(&req)
if err != nil {
return nil, err
}
resp, err := conn.clientConn.Read()
if err != nil {
return nil, err
}
return resp, nil
}
示例5: send
// sent a request off to twitter. Returns the response's body or an error.
func send(url, method string, form map[string][]string, client *Client, body string) (result string, err os.Error) {
req := new(http.Request)
req.Method = method
req.RawURL = url
req.Host = URLHost
req.Referer = "none"
req.UserAgent = HTTPUserAgent
req.Form = form
req.Header = map[string]string{
"Connection": "Keep Alive",
"Authorization": getAuthHeader(client),
}
req.Body = strings.NewReader(body)
req.URL, err = http.ParseURL(req.RawURL)
if err != nil {
return "", err
}
// send request
resp := new(http.Response)
resp, err = http.Send(req)
if err != nil {
return "", err
}
result = getResponseBody(resp)
return result, nil
}
示例6: Update
// PUT /resource/id
func (client *Client) Update(id string, body string) (*http.Response, os.Error) {
var request *http.Request
var err os.Error
if request, err = client.newRequest("PUT", id); err != nil {
return nil, err
}
request.Body = nopCloser{bytes.NewBufferString(body)}
return client.Request(request)
}
示例7: httpExecute
func (c *Consumer) httpExecute(
method string, url string, body string, oauthParams *OrderedParams) (*http.Response, os.Error) {
if c.debug {
fmt.Println("httpExecute(method: " + method + ", url: " + url)
}
var req http.Request
req.Method = method
req.Header = http.Header{}
req.Body = newStringReadCloser(body)
parsedurl, err := http.ParseURL(url)
if err != nil {
return nil, os.NewError("ParseUrl: " + err.String())
}
req.URL = parsedurl
oauthHdr := "OAuth "
for pos, key := range oauthParams.Keys() {
if pos > 0 {
oauthHdr += ","
}
oauthHdr += key + "=\"" + oauthParams.Get(key) + "\""
}
if c.debug {
fmt.Println("AUTH-HDR: " + oauthHdr)
}
req.Header.Add("Authorization", oauthHdr)
resp, err := c.HttpClient.Do(&req)
if err != nil {
return nil, os.NewError("Do: " + err.String())
}
debugHeader := ""
for k, vals := range req.Header {
for _, val := range vals {
debugHeader += "[key: " + k + ", val: " + val + "]"
}
}
if resp.StatusCode != http.StatusOK {
bytes, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
return nil, os.NewError("HTTP response is not 200/OK as expected. Actual response: \n" +
"\tResponse Status: '" + resp.Status + "'\n" +
"\tResponse Code: " + strconv.Itoa(resp.StatusCode) + "\n" +
"\tResponse Body: " + string(bytes) + "\n" +
"\tRequst Headers: " + debugHeader)
}
return resp, err
}
示例8: sendBody
func sendBody(s Sender, url, method, bodyType string, body io.Reader) (r *http.Response, err os.Error) {
var req http.Request
req.Method = method
req.RawURL = url
req.Body = nopCloser{body}
req.Header = map[string]string{
"Content-Type": bodyType,
}
req.TransferEncoding = []string{"chunked"}
return Send(s, &req)
}
示例9: sendFromQueue
// This function is launched async as a go routine. It tries to send a message
// to a remote server and sends a bool to nextChannel to indicate whether this
// has succeeded or not. It is not allowed to run this function multiple times in parallel
// for the same FederationGateway.
func (self *FederationGateway) sendFromQueue(req *WaveletUpdateRequest) {
// No HTTP connection open yet?
if self.connection == nil {
con, err := net.Dial("tcp", "", fmt.Sprintf("%v:%v", self.manifest.HostName, self.manifest.Port))
if err != nil {
// TODO: Good error handling
log.Println("Failed connecting to ", self.manifest, err)
self.nextChannel <- false
return
}
self.connection = http.NewClientConn(con, nil)
}
// Build the HTTP request
var hreq http.Request
hreq.Host = self.manifest.Domain
hreq.Header = make(map[string]string)
hreq.RawURL = fmt.Sprintf("http://%v:%v/fed%v", self.manifest.HostName, self.manifest.Port, req.uri)
hreq.Method = "PUT"
hreq.Body = NewRequestBody(req.Data)
hreq.ContentLength = int64(len(req.Data))
hreq.Header["Content-Type"] = req.MimeType
log.Println("Sending WaveletUpdate to remote server ", hreq.RawURL)
// Send the HTTP request
self.connection.Write(&hreq)
// Read the HTTP response
hres, err := self.connection.Read()
if err != nil {
log.Println("Error reading HTTP response from ", self.manifest, err)
// TODO: Better error handling
self.connection.Close()
self.connection = nil
self.nextChannel <- false
return
}
log.Println("After sending WaveletUpdate, status code is ", hres.StatusCode)
// Success in sending the wavelet update?
if hres.StatusCode == 200 {
self.nextChannel <- true
return
}
// Sending the wavelet update failed
self.nextChannel <- false
}
示例10: ReadRequestBody
// reads the request body and replaces the buffer with self
// returns nil if the body is multipart and not replaced
func ReadRequestBody(r *http.Request) (sb *StringBody, err os.Error) {
ct := r.Header.Get("Content-Type")
// leave it on the buffer if we're multipart
if strings.SplitN(ct, ";", 2)[0] != "multipart/form-data" && r.ContentLength > 0 {
sb = new(StringBody)
const maxFormSize = int64(10 << 20) // 10 MB is a lot of text.
b, e := ioutil.ReadAll(io.LimitReader(r.Body, maxFormSize+1))
if e != nil {
return nil, e
}
sb.BodyString = string(b)
sb.Close() // to create our buffer
r.Body.Close()
r.Body = sb
return sb, nil
}
return nil, nil // ignore
}
示例11: nmcPOST
func nmcPOST(body *bytes.Buffer) (response *http.Response, err os.Error) {
client := http.Client{}
var req http.Request
req.Method = "POST"
req.ProtoMajor = 1
req.ProtoMinor = 1
req.Close = true
req.Body = ioutil.NopCloser(body)
req.Header = http.Header{
"Content-Type": []string{"text/plain"},
"Content-Length": []string{strconv.Itoa(body.Len())},
}
req.ContentLength = int64(body.Len())
req.URL = options.nmcURL
return client.Do(&req)
}
示例12: Post
// Post issues a POST to the specified URL.
//
// Caller should close r.Body when done reading it.
func Post(url, user, pwd, bodyType string, body io.Reader) (r *http.Response, err os.Error) {
var req http.Request
req.Method = "POST"
req.Body = nopCloser{body}
req.Header = map[string]string{
"Content-Type": bodyType,
"Transfer-Encoding": "chunked",
"X-Twitter-Client": "gotweet",
"X-Twitter-Version": "0.1",
"Authorization": "Basic " + encodedUsernameAndPassword(user, pwd),
}
req.URL, err = http.ParseURL(url)
if err != nil {
return nil, err
}
return send(&req)
}
示例13: post
// post taken from Golang modified to allow Headers to be pased
func post(url string, headers map[string]string, body io.Reader) (r *http.Response, err os.Error) {
var req http.Request
req.Method = "POST"
req.ProtoMajor = 1
req.ProtoMinor = 1
req.Close = true
req.Body = nopCloser{body}
for k, v := range headers {
req.Header.Add(k, v)
}
req.TransferEncoding = []string{"chunked"}
req.URL, err = http.ParseURL(url)
if err != nil {
return nil, err
}
return send(&req)
}
示例14: connect
func (conn *streamConn) connect() (*http.Response, os.Error) {
if conn.stale {
return nil, os.NewError("Stale connection")
}
var tcpConn net.Conn
var err os.Error
if proxy := os.Getenv("HTTP_PROXY"); len(proxy) > 0 {
proxy_url, _ := url.Parse(proxy)
tcpConn, err = net.Dial("tcp", proxy_url.Host)
} else {
tcpConn, err = net.Dial("tcp", conn.url.Host+":443")
}
if err != nil {
return nil, err
}
cf := &tls.Config{Rand: rand.Reader, Time: time.Nanoseconds}
ssl := tls.Client(tcpConn, cf)
conn.clientConn = http.NewClientConn(ssl, nil)
var req http.Request
req.URL = conn.url
req.Method = "GET"
req.Header = http.Header{}
req.Header.Set("Authorization", "Basic "+conn.authData)
if conn.postData != "" {
req.Method = "POST"
req.Body = nopCloser{bytes.NewBufferString(conn.postData)}
req.ContentLength = int64(len(conn.postData))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
resp, err := conn.clientConn.Do(&req)
if err != nil {
return nil, err
}
return resp, nil
}
示例15: authPost
// Post issues a POST to the specified URL.
//
// Caller should close r.Body when done reading it.
func authPost(url, user, pwd, client, clientURL, version, agent, bodyType string,
body io.Reader) (r *http.Response, err os.Error) {
var req http.Request
req.Method = "POST"
req.Body = body.(io.ReadCloser)
req.Header = map[string]string{
"Content-Type": bodyType,
"Transfer-Encoding": "chunked",
"User-Agent": agent,
"X-FluidDB-Client": client,
"X-FluidDB-Client-URL": clientURL,
"X-FluidDB-Version": version,
"Authorization": "Basic " + encodedUsernameAndPassword(user, pwd),
}
req.URL, err = http.ParseURL(url)
if err != nil {
return nil, err
}
return send(&req)
}