douyang2530 2018-06-06 19:47
浏览 52
已采纳

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

The comment for the field Response in the type http.Request is as follows.

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

However, it seems to me that this field is not being populated during requests, as it is implied that it is. Consider the following example:

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))
}

If I compile and run this code and navigate to localhost:8080/a, then I get redirected to localhost:8080/b and the server prints <nil> to the console. But shouldn't it be printing out a non-nil value, since the request is coming as the result of a redirect?

  • 写回答

1条回答 默认 最新

  • douchuxun4162 2018-06-06 19:56
    关注

    In your sample, the redirect is happening in the browser; the server doesn't get to know what response generated the redirect. That field is populated when making HTTP requests from a Go app; for example, if you use http.Client to request a URL, and the response is a redirect, it generates a new Request for the redirect URL, and in that Request, the Response field will be populated with the response that triggered that redirect.

    This is evidenced in the source for http.Client: https://golang.org/src/net/http/client.go#L669

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程