Golang Request.Body Examples

Golang Request.Body - 30 examples found. These are the top rated real world Golang examples of net/http.Request.Body extracted from open source projects. You can rate examples to help us improve the quality of examples.
Example #1
0
func (client ApiClient) do(req *http.Request, body interface{}, responseBody interface{}) error {
	var buf *bytes.Buffer
	if body != nil {
		switch body.(type) {
		case io.Reader:
			req.Body = ioutil.NopCloser(body.(io.Reader))
		default:
			buf = new(bytes.Buffer)
			encoder := client.encoder(buf)
			if err := encoder.Encode(body); err != nil {
				return err
			}
			req.Body = ioutil.NopCloser(buf)
		}
	}

	if resp, err := http.DefaultClient.Do(req); err != nil {
		return err
	} else if err = client.errorFromResponse(resp); err != nil {
		return err
	} else {
		if responseBody != nil {
			defer resp.Body.Close()
			decoder := client.decoder(resp.Body)
			return decoder.Decode(responseBody)
		}
		return nil
	}
}
Example #2
0
func CopyHttpRequest(r *http.Request) *http.Request {
	reqCopy := new(http.Request)

	if r == nil {
		return reqCopy
	}

	*reqCopy = *r

	if r.Body != nil {
		defer r.Body.Close()

		// Buffer body data
		var bodyBuffer bytes.Buffer
		bodyBuffer2 := new(bytes.Buffer)

		io.Copy(&bodyBuffer, r.Body)
		*bodyBuffer2 = bodyBuffer

		// Create new ReadClosers so we can split output
		r.Body = ioutil.NopCloser(&bodyBuffer)
		reqCopy.Body = ioutil.NopCloser(bodyBuffer2)
	}

	return reqCopy
}
Example #3
0
// dispatchRequest sends a request to the server, and interprets the response.
// Client-side errors will return an empty response and a non-nil error.  For
// server-side errors however (i.e. responses with a non 2XX status code), the
// returned error will be ServerError and the returned body will reflect the
// server's response.  If the server returns a 503 response with a 'Retry-after'
// header, the request will be transparenty retried.
func (client Client) dispatchRequest(request *http.Request) ([]byte, error) {
	// First, store the request's body into a byte[] to be able to restore it
	// after each request.
	bodyContent, err := readAndClose(request.Body)
	if err != nil {
		return nil, err
	}
	for retry := 0; retry < NumberOfRetries; retry++ {
		// Restore body before issuing request.
		newBody := ioutil.NopCloser(bytes.NewReader(bodyContent))
		request.Body = newBody
		body, err := client.dispatchSingleRequest(request)
		// If this is a 503 response with a non-void "Retry-After" header: wait
		// as instructed and retry the request.
		if err != nil {
			serverError, ok := err.(ServerError)
			if ok && serverError.StatusCode == http.StatusServiceUnavailable {
				retry_time_int, errConv := strconv.Atoi(serverError.Header.Get(RetryAfterHeaderName))
				if errConv == nil {
					select {
					case <-time.After(time.Duration(retry_time_int) * time.Second):
					}
					continue
				}
			}
		}
		return body, err
	}
	// Restore body before issuing request.
	newBody := ioutil.NopCloser(bytes.NewReader(bodyContent))
	request.Body = newBody
	return client.dispatchSingleRequest(request)
}
Example #4
0
func (t *logTransport) RoundTrip(req *http.Request) (*http.Response, 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
}
Example #5
0
func ReadBody(req *http.Request) *string {
	save := req.Body
	var err error
	if req.Body == nil {
		req.Body = nil
	} else {
		save, req.Body, err = drainBody(req.Body)
		if err != nil {
			return nil
		}
	}
	b := bytes.NewBuffer([]byte(""))
	chunked := len(req.TransferEncoding) > 0 && req.TransferEncoding[0] == "chunked"
	if req.Body == nil {
		return nil
	}
	var dest io.Writer = b
	if chunked {
		dest = httputil.NewChunkedWriter(dest)
	}
	_, err = io.Copy(dest, req.Body)
	if chunked {
		dest.(io.Closer).Close()
	}
	req.Body = save
	body := b.String()
	return &body
}
Example #6
0
// handle request body
func (conn Conn) handleBody(req *http.Request, body io.Reader) {
	rc, ok := body.(io.ReadCloser)
	if !ok && body != nil {
		rc = ioutil.NopCloser(body)
	}
	req.Body = rc
	switch v := body.(type) {
	case *bytes.Buffer:
		req.ContentLength = int64(v.Len())
	case *bytes.Reader:
		req.ContentLength = int64(v.Len())
	case *strings.Reader:
		req.ContentLength = int64(v.Len())
	case *os.File:
		req.ContentLength = tryGetFileSize(v)
	}
	req.Header.Set(HTTPHeaderContentLength, strconv.FormatInt(req.ContentLength, 10))

	// md5
	if req.Body != nil {
		buf, _ := ioutil.ReadAll(req.Body)
		req.Body = ioutil.NopCloser(bytes.NewReader(buf))
		sum := md5.Sum(buf)
		b64 := base64.StdEncoding.EncodeToString(sum[:])
		req.Header.Set(HTTPHeaderContentMD5, b64)
	}
}