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

时间:2018-06-06 19:47:50

标签: go webserver httprequest httpresponse http-redirect

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

// 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值,因为请求是作为重定向的结果而来的吗?

1 个答案:

答案 0 :(得分:1)

在您的示例中,重定向发生在浏览器中;服务器无法知道重定向生成了什么响应。从 Go应用程序发出HTTP请求时,将填充该字段;例如,如果您使用http.Client来请求网址,并且响应是重定向,则会为重定向网址生成新的Request,并在中生成 {{1 }},Request字段将填充触发该重定向的响应。

Responsehttps://golang.org/src/net/http/client.go#L669

的来源证明了这一点