gpt4 book ai didi

go - 如何在golang中制作绝对路径http重定向

转载 作者:IT王子 更新时间:2023-10-29 00:35:29 36 4
gpt4 key购买 nike

我正在阅读源代码 goto ,我在 goto/talk/0/main.go 中找到了下面的代码:

http.Redirect(w, r, url, http.StatusFound)

根据上下文,url 是一个绝对路径,需要一个绝对路径重定向。但是作为 golang/http/redirect提到:

Redirect replies to the request with a redirect to url, which may be a path relative to the request path.

它的结果是相对路径重定向。我不知道 http.Redirect 以前是否做过绝对路径重定向,但现在不会了。

那么如何在golang中进行绝对路径重定向呢?我在网上搜索,但什么也没找到,谁能帮帮我?提前致谢。

最佳答案

当您转到 http.Redirect 的 golang 文档时,您实际上可以单击蓝色标题:

func Redirect

它将带您到不言自明的源代码 list :

// 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 := "<a href=\"" + htmlEscape(urlStr) + "\">" + statusText[code] +
"</a>.\n"
fmt.Fprintln(w, note)
}
}

这个技巧也适用于其他函数。

关于go - 如何在golang中制作绝对路径http重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11930801/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com