how to make an absolute path http redirect in golang
我在读源代码goto,我在goto/talk/0/main.go中找到了下面的代码:
1 | http.Redirect(w, r, url, http.StatusFound) |
根据上下文,
Redirect replies to the request with a redirect to url, which may be a path relative to the request path.
号
其结果是相对路径重定向。我不知道
那么,我如何才能在戈兰进行绝对路径重定向呢?我在网上搜了一下,却什么也没找到,有人能帮我吗?事先谢谢。
当您转到golang documentation for
func Redirect
号
它将带您进入源代码列表,这是不言而喻的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | // Redirect replies to the request with a redirect to url, // which may be a path relative to the request path. func Redirect(w ResponseWriter, r *Request, urlStr string, code int) { if u, err := url.Parse(urlStr); err == nil { // If url was relative, make absolute by // combining with request path. // The browser would probably do this for us, // but doing it ourselves is more reliable. // NOTE(rsc): RFC 2616 says that the Location // line must be an absolute URI, like //"http://www.google.com/redirect/", // not a path like"/redirect/". // Unfortunately, we don't know what to // put in the host name section to get the // client to connect to us again, so we can't // know the right absolute URI to send back. // Because of this problem, no one pays attention // to the RFC; they all send back just a new path. // So do we. oldpath := r.URL.Path if oldpath =="" { // should not happen, but avoid a crash if it does oldpath ="/" } if u.Scheme =="" { // no leading http://server if urlStr =="" || urlStr[0] != '/' { // make relative path absolute olddir, _ := path.Split(oldpath) urlStr = olddir + urlStr } var query string if i := strings.Index(urlStr,"?"); i != -1 { urlStr, query = urlStr[:i], urlStr[i:] } // clean up but preserve trailing slash trailing := strings.HasSuffix(urlStr,"/") urlStr = path.Clean(urlStr) if trailing && !strings.HasSuffix(urlStr,"/") { urlStr +="/" } urlStr += query } } w.Header().Set("Location", urlStr) w.WriteHeader(code) // RFC2616 recommends that a short note"SHOULD" be included in the // response because older user agents may not understand 301/307. // Shouldn't send the response for POST or HEAD; that leaves GET. if r.Method =="GET" { note :="" + statusText[code] + ". " fmt.Fprintln(w, note) } } |
这个技巧也适用于其他功能。
我最后发现,为了执行绝对路径重定向,