1

I saw this post by someone here but there are no answers: Redirecting https://www.domain.com to https://domain.com in Go

I tried to see if I could find a way to check if the request was made with a www url by checking the variables in *http.Request variable but all I got was relative paths and empty strings "".

I tried to fmt.Println() these variables:

func handleFunc(w http.ResponseWriter, r *http.Request) { fmt.Println(r.URL.string()) fmt.Println(r.Host) fmt.Println(r.RequestURI) } 

But none of these variables contained the absolute path with the www part. How can I check if a request was made from a www url? I want to figure this out so that I can redirect from www to non-www.

Is this really not even possible in Go? Some people suggested putting nginx in front of Go, but there has to be a way without nginx right? Do I really need to install and use nginx in front of Go just to do a simple redirect from www to non-www? This does not seem like a good solution to a seemingly small problem.

Is there no way to achieve this?

2
  • Of course you can do this in Go, because Go is a general-purpose programming language. The real question is whether it is possible to do so in the HTTP library you have chosen to use. So what HTTP library are you using? Can you provide a link to its documentation? Have you tried looking at the Host HTTP header in the request? Commented Aug 8, 2016 at 21:58
  • The www subdomain isn't part of the path, it will be part of the host field. Please show an example of what you're seeing, since it should be present in the Request.Host or Request.URL. Commented Aug 8, 2016 at 22:00

1 Answer 1

8

Wrap your handlers with a redirector:

func wwwRedirect(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if host := strings.TrimPrefix(r.Host, "www."); host != r.Host { // Request host has www. prefix. Redirect to host with www. trimmed. u := *r.URL u.Host = host u.Scheme = "https" http.Redirect(w, r, u.String(), http.StatusFound) return } h.ServeHTTP(w, r) }) } 

Use the redirector like this:

log.Fatal(http.ListenAndServeTLS(addr, certFile, keyFile, wwwRedirect(handler)) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.