英文:
What original type is passed in ServeHTTP's http.ResponseWriter interface?
问题
在研究net/http
时,我实际上想知道Go语言如何将http.Response
返回给监听器。从这个答案中,我发现传递给ServeHTTP
的类型是http.Response
,但事实并非如此,因为在编译时,下面的代码会抛出错误。这意味着http.Response
并没有实现http.ResponseWriter
接口。我很好奇,到底是哪种类型实现了http.ResponseWriter
接口?
# command-line-arguments
./server1.go:9:20: http.Response.Header is a field, not a method
./server1.go:9:20: impossible type assertion:
http.Response does not implement http.ResponseWriter (missing Header method)
func handler(resp http.ResponseWriter, req *http.Request){
actualresp := resp.(http.Response) //https://tour.golang.org/methods/15
resp.Write([]byte("Hello Web, from go"))
}
func main(){
http.HandleFunc("/api", handler)
http.ListenAndServe(":8000", nil)
}
英文:
While studying net/http
I actually wanted to know that how go returns http.Response
to listener. From this answer, I found that http.Response type is passed to ServeHTTP, but that is not the case because on compilation below code throw error. Which means http.Response
does not implement http.ResponseWriter
interface. I am curious what is the type which implements http.ResponseWriter
interface?
# command-line-arguments
./server1.go:9:20: http.Response.Header is a field, not a method
./server1.go:9:20: impossible type assertion:
http.Response does not implement http.ResponseWriter (missing Header method)
func handler(resp http.ResponseWriter, req *http.Request){
actualresp := resp.(http.Response) //https://tour.golang.org/methods/15
resp.Write([]byte("Hello Web, from go"))
}
func main(){
http.HandleFunc("/api", handler)
http.ListenAndServe(":8000", nil)
}
答案1
得分: 2
http.Response 只有以下几个方法:
func (r *Response) Cookies() []*Cookie
func (r *Response) Location() (*url.URL, error)
func (r *Response) ProtoAtLeast(major, minor int) bool
func (r *Response) Write(w io.Writer) error
它没有实现 http.ResponseWriter 接口,该接口需要以下方法:
Header() Header
Write([]byte) (int, error)
WriteHeader(statusCode int)
所以很明显 http.Response
不能用作 http.ResponseWriter
。
相反,正如你链接的答案所提到的,使用了非导出的 http.response。你可以在 代码中 找到关于在服务器端进行写入的详细描述。
英文:
http.Response has the following methods only:
func (r *Response) Cookies() []*Cookie
func (r *Response) Location() (*url.URL, error)
func (r *Response) ProtoAtLeast(major, minor int) bool
func (r *Response) Write(w io.Writer) error
This does not implement the http.ResponseWriter interface which requires:
Header() Header
Write([]byte) (int, error)
WriteHeader(statusCode int)
So clearly http.Response
cannot be used as a http.ResponseWriter
.
Instead, and as the answer you linked to mentions, the non-exported http.response is used. You can find a description of the life of a write on the http server side in the code.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论