Skip to content

About request Host field and copy Cookie in reverseproxy.go  #1886

@gopherbot

Description

@gopherbot

by BG5SBK:

I try to use "reverseproxy.go" to make a simple http proxy, but it's not work.

The "Director" function in "reverseproxy.go" not set request's Host
field as target URL's Host.

So, when target is a virtual host will not work.

Below code work well for me:

    o := new(http.Request)

    *o = *r

    o.Host       = targetURL.Host
    o.URL.Scheme = targetURL.Scheme
    o.URL.Host   = targetURL.Host
    o.URL.Path   = singleJoiningSlash(targetURL.Path, o.URL.Path)

    if q := o.URL.RawQuery; q != "" {
        o.URL.RawPath = o.URL.Path + "?" + q
    } else {
        o.URL.RawPath = o.URL.Path
    }

    o.URL.RawQuery = targetURL.RawQuery

    o.Proto      = "HTTP/1.1"
    o.ProtoMajor = 1
    o.ProtoMinor = 1
    o.Close      = false

Just one line, the "o.Host = targetURL.Host" different with
"reverseproxy.go"

And the "ServeHTTP" function in "reverseproxy.go" the Cookie in
target response not copy to response.

Below code work well for me:

    for _, c := range res.SetCookie {
        w.Header().Add("Set-Cookie", c.Raw)
    }

Without this code, some website can't login.

Below two attachements is the test code that try to proxy request to
"http://www.baidu.com";

The first attachment "main.go", when a request in, the server throw :
"proxy error: unexpected EOF".

And second attachment "main3.go", I copy out "reverseproxy.go" and
make some hack and then it work correctly.

Attachments:

  1. main.go (333 bytes)
  2. main3.go (1545 bytes)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions