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

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

报告相同问题?