Is the full, absolute URL of an HTTP request directly available?

2,885 views
Skip to first unread message

Peter Lacey

unread,
Apr 18, 2014, 4:38:38 PM4/18/14
to golan...@googlegroups.com
I'm looking to access the full URL of an HTTP request.  When the following code is run with:

$ curl "http://localhost:8080/foo"

It prints out:

/foo
/foo

/*  **** Code ****
package main

import (
    "fmt"
    "net/http"
)

func someHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Println(r.URL.String())
    fmt.Println(r.RequestURI)
}

func main() {
    http.HandleFunc("/", someHandler)
    http.ListenAndServe(":8080", nil)
}

Is the full URL tucked away any where?  If not, I'm curious what the reasoning might be?  Or is there a simple call to reassemble the full URL from the request?  url.URL.String() doesn't seem to do that, as I would have expected.

I've googled the heck out of this, but came up dry.

Thanks in advance,
Pete

Peter Lacey

unread,
Apr 18, 2014, 5:17:08 PM4/18/14
to golan...@googlegroups.com
Thanks, Islan.  That's what I figured.  I admit, though, it seems odd that this isn't more accessible.

-- Pete

On Friday, April 18, 2014 5:12:46 PM UTC-4, Islan Dberry wrote:
It is not directly available, but you can be able to assemble it:

u := r.URL

// The scheme is http because that's the only protocol your server handles.
u.Scheme = "http" 

// If client specified a host header, then use it for the full URL.
u.Host = r.Host   

// Otherwise, use your server's host name. 
if u.Host == "" {
   u.Host = "your-host-name.com"

Alex Zorin

unread,
Apr 18, 2014, 5:18:47 PM4/18/14
to golan...@googlegroups.com
To expand on that, not all parts of the URL are available to the server. For example, :8080 in your example is interpreted by the HTTP client and not sent to the server in the request. So to reassemble it, you would need foreknowledge that the server runs on port 8080.

Brad Fitzpatrick

unread,
Apr 18, 2014, 5:31:59 PM4/18/14
to Peter Lacey, golang-nuts
It's not more accessible because it's not always there on the wire in the HTTP protocol.

And when proxies are involved, the URL the user sees in their browser (which might be more similar to where you want to redirect them) might not anything resemble what Go sees (might be a different scheme, host, and port).



--
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.

Peter Lacey

unread,
Apr 18, 2014, 6:08:46 PM4/18/14
to golan...@googlegroups.com
Thanks Alex and Brad,

That additional info help clarify things quite a bit.

BTW, this is a very helpful mailing list.  So thanks for that too.  Once I've internalized Go some more, I hope to contribute answers and not just questions.

-- Pete
Reply all
Reply to author
Forward
Message has been deleted
0 new messages