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

标签 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 吗?值,因为请求是重定向的结果?

最佳答案

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

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

关于go - 为什么没有填充此 HTTP 请求的响应字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50728423/

相关文章:

java - 从 kafka 消费者向服务发出 100 万个单独的 http 请求是个好主意吗?

google-app-engine - 如果我有 Order 子句,Google App Engine 数据存储区不会返回任何行

go - 如何使 Go append 在范围循环内工作

string - 使用 Go 的 archive/zip 创建带有 Unicode 文件名的 zip 存档

c - 多连接Web服务器C

go - 下载的 excelize xlsx 文件已损坏

go - 去tcpdump的“exec.Command”什么都不做

python - 使用 eventlet 处理并发请求或线程化 Flask SocketIO

ruby-on-rails - Spotify 网络 API : Basic authorization

http请求命令行工具