Merge from mainline (167278:168000).
[official-gcc/graphite-test-results.git] / libgo / go / http / dump.go
blob73ac97973999d4a6476665077b07c8faeffbbe8a
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 package http
7 import (
8 "bytes"
9 "io"
10 "os"
14 // One of the copies, say from b to r2, could be avoided by using a more
15 // elaborate trick where the other copy is made during Request/Response.Write.
16 // This would complicate things too much, given that these functions are for
17 // debugging only.
18 func drainBody(b io.ReadCloser) (r1, r2 io.ReadCloser, err os.Error) {
19 var buf bytes.Buffer
20 if _, err = buf.ReadFrom(b); err != nil {
21 return nil, nil, err
23 if err = b.Close(); err != nil {
24 return nil, nil, err
26 return nopCloser{&buf}, nopCloser{bytes.NewBuffer(buf.Bytes())}, nil
29 // DumpRequest returns the wire representation of req,
30 // optionally including the request body, for debugging.
31 // DumpRequest is semantically a no-op, but in order to
32 // dump the body, it reads the body data into memory and
33 // changes req.Body to refer to the in-memory copy.
34 func DumpRequest(req *Request, body bool) (dump []byte, err os.Error) {
35 var b bytes.Buffer
36 save := req.Body
37 if !body || req.Body == nil {
38 req.Body = nil
39 } else {
40 save, req.Body, err = drainBody(req.Body)
41 if err != nil {
42 return
45 err = req.Write(&b)
46 req.Body = save
47 if err != nil {
48 return
50 dump = b.Bytes()
51 return
54 // DumpResponse is like DumpRequest but dumps a response.
55 func DumpResponse(resp *Response, body bool) (dump []byte, err os.Error) {
56 var b bytes.Buffer
57 save := resp.Body
58 savecl := resp.ContentLength
59 if !body || resp.Body == nil {
60 resp.Body = nil
61 resp.ContentLength = 0
62 } else {
63 save, resp.Body, err = drainBody(resp.Body)
64 if err != nil {
65 return
68 err = resp.Write(&b)
69 resp.Body = save
70 resp.ContentLength = savecl
71 if err != nil {
72 return
74 dump = b.Bytes()
75 return