为什么没有填充此 HTTP 请求的响应字段?

Why isn't the Response field of this HTTP Request being populated?

类型http.Request中字段Response的注释如下。

// Response is the redirect response which caused this request
// to be created. This field is only populated during client
// redirects.
Response *Response

但是,在我看来,这个字段在请求期间没有被填充,因为它暗示它是。考虑以下示例:

package main

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

func handleA(writer http.ResponseWriter, request *http.Request) {
  http.Redirect(writer, request, "/b", http.StatusSeeOther)
}

func handleB(writer http.ResponseWriter, request *http.Request) {
  fmt.Println(request.Response)
}

func main() {
  http.HandleFunc("/a", handleA)
  http.HandleFunc("/b", handleB)
  log.Fatal(http.ListenAndServe(":8080", nil))
}

如果我编译并 运行 这段代码并导航到 localhost:8080/a,那么我将被重定向到 localhost:8080/b 并且服务器将 <nil> 打印到控制台。但是它不应该打印出一个非 nil 值,因为请求是重定向的结果吗?

在您的示例中,重定向发生在浏览器中;服务器不知道是什么响应生成了重定向。当从 一个 Go 应用发出 HTTP 请求 时,该字段被填充;例如,如果您使用 http.Client 请求 URL,并且响应是重定向,它会为重定向 URL 生成一个新的 Request,并且在 that RequestResponse 字段将填充触发该重定向的响应。

http.Client 的来源证明了这一点:https://golang.org/src/net/http/client.go#L669