The Go Programming Language

Source file src/pkg/http/dump.go

     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.
     4	
     5	package http
     6	
     7	import (
     8		"bytes"
     9		"io"
    10		"io/ioutil"
    11		"os"
    12	)
    13	
    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
    22		}
    23		if err = b.Close(); err != nil {
    24			return nil, nil, err
    25		}
    26		return ioutil.NopCloser(&buf), ioutil.NopCloser(bytes.NewBuffer(buf.Bytes())), nil
    27	}
    28	
    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	// The documentation for Request.Write details which fields
    35	// of req are used.
    36	func DumpRequest(req *Request, body bool) (dump []byte, err os.Error) {
    37		var b bytes.Buffer
    38		save := req.Body
    39		if !body || req.Body == nil {
    40			req.Body = nil
    41		} else {
    42			save, req.Body, err = drainBody(req.Body)
    43			if err != nil {
    44				return
    45			}
    46		}
    47		err = req.Write(&b)
    48		req.Body = save
    49		if err != nil {
    50			return
    51		}
    52		dump = b.Bytes()
    53		return
    54	}
    55	
    56	// DumpResponse is like DumpRequest but dumps a response.
    57	func DumpResponse(resp *Response, body bool) (dump []byte, err os.Error) {
    58		var b bytes.Buffer
    59		save := resp.Body
    60		savecl := resp.ContentLength
    61		if !body || resp.Body == nil {
    62			resp.Body = nil
    63			resp.ContentLength = 0
    64		} else {
    65			save, resp.Body, err = drainBody(resp.Body)
    66			if err != nil {
    67				return
    68			}
    69		}
    70		err = resp.Write(&b)
    71		resp.Body = save
    72		resp.ContentLength = savecl
    73		if err != nil {
    74			return
    75		}
    76		dump = b.Bytes()
    77		return
    78	}

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.