Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

net/http: http.Redirect cause redirect loop #9963

Closed
shit386 opened this issue Feb 23, 2015 · 2 comments
Closed

net/http: http.Redirect cause redirect loop #9963

shit386 opened this issue Feb 23, 2015 · 2 comments

Comments

@shit386
Copy link

shit386 commented Feb 23, 2015

expect: Location: http://domain.com
got:Location: http://www.domain.com

        if 0 == strings.Index(req.Host,"www") {
                url := "http://domain.com" + req.RequestURI
                res.Header().Set("Location",url)
                fmt.Println(url)//这里还是:http://domain.com
                res.WriteHeader(http.StatusMovedPermanently) 
                        //到浏览器就变成(Location: http://www.domain.com)
                res.Write(nil)
                return
            }
        if 0 == strings.Index(req.Host,"www") {
                url := "http://domain.com" + req.RequestURI
                fmt.Println(url)//这里还是:http://domain.com
                    http.Redirect(res,req,url,http.StatusMovedPermanently)
                //到浏览器就变成:(Location: http://www.domain.com)
                    return
        }
@leepa
Copy link
Contributor

leepa commented Feb 23, 2015

I cannot reproduce this with your code:

package main

import (
    "fmt"
    "net/http"
    "strings"
)

func handler(w http.ResponseWriter, r *http.Request) {
    if 0 == strings.Index(r.Host, "www") {
        url := "http://domain.com" + r.RequestURI
        w.Header().Set("Location", url)
        fmt.Println(url)
        w.WriteHeader(http.StatusMovedPermanently)
        w.Write(nil)
        return
    }
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}
 curl -H 'Host: www.foobar.com' -v http://localhost:8080/
* Hostname was NOT found in DNS cache
*   Trying ::1...
* Connected to localhost (::1) port 8080 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.37.1
> Accept: */*
> Host: www.foobar.com
>
< HTTP/1.1 301 Moved Permanently
< Location: http://domain.com/
< Date: Mon, 23 Feb 2015 07:51:58 GMT
< Content-Length: 0
< Content-Type: text/plain; charset=utf-8
<
* Connection #0 to host localhost left intact

@shit386
Copy link
Author

shit386 commented Feb 24, 2015

tnks
u r right

@shit386 shit386 closed this as completed Feb 24, 2015
@golang golang locked and limited conversation to collaborators Jun 25, 2016
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants