Correct use of http.RoundTripper

2,779 views
Skip to first unread message

Owen

unread,
Apr 1, 2014, 5:46:31 PM4/1/14
to golan...@googlegroups.com
Hi folks,

I'm trying to understand more of http.RoundTripper. The doc mentions this for the interface:

type RoundTripper interface {
        // RoundTrip executes a single HTTP transaction, returning
        // the Response for the request req.  RoundTrip should not
        // attempt to interpret the response.  In particular,
        // RoundTrip must return err == nil if it obtained a response,
        // regardless of the response's HTTP status code.  A non-nil
        // err should be reserved for failure to obtain a response.
        // Similarly, RoundTrip should not attempt to handle
        // higher-level protocol details such as redirects,
        // authentication, or cookies.
        //
        // RoundTrip should not modify the request, except for
        // consuming and closing the Body. The request's URL and
        // Header fields are guaranteed to be initialized.
        RoundTrip(*Request) (*Response, error)
}

It says "RoundTrip should not modify the request". But I read a bit on how RoundTripper is used and I didn't see any obvious problem of mutating Request (http://golang.org/src/pkg/net/http/client.go?s=2115:2857#L168). I wonder if it's ok to create a delegating RoundTripper like this: I http://play.golang.org/p/pem5CZKInL. Will there be any side effect?

Thanks,
Owen

Kyle Lemons

unread,
Apr 9, 2014, 8:53:52 PM4/9/14
to Owen, golang-nuts
You can duplicate the request and then send it off.  You just shouldn't modify the memory to which the original request points.
 
Thanks,
Owen

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

mislav....@gmail.com

unread,
Sep 12, 2014, 5:48:45 PM9/12/14
to golan...@googlegroups.com, jing...@gmail.com


On Wednesday, April 9, 2014 5:53:52 PM UTC-7, Kyle Lemons wrote:

You can duplicate the request and then send it off.  You just shouldn't modify the memory to which the original request points.

Thank you, Kyle. We need to edit the `request.URL.Host` property as well. So when we duplicate the request, we should also duplicate the URL value right?

Something like:

    req2.URL, _ = url.Parse(req.URL)
    req2.URL.Host = "example.com"

Is there a better way to clone a URL object?

Matt Harden

unread,
Sep 12, 2014, 10:12:15 PM9/12/14
to mislav....@gmail.com, golang-nuts, jing...@gmail.com
A URL object can be cloned just by copying, since all its fields are exported.

var url2 net.URL = *req.URL

The request can be cloned in the same way, but as you mentioned the URL needs to be cloned separately since it's a pointer.

--
Reply all
Reply to author
Forward
0 new messages