【问题标题】:Why isn't the Response field of this HTTP Request being populated?为什么没有填充此 HTTP 请求的响应字段?
【发布时间】:2018-11-16 14:42:45
【问题描述】:

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 webserver httprequest httpresponse http-redirect


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    相关资源
    最近更新 更多