在 Go HTTP 处理程序中,为什么 ResponseWriter 是一个值而 Request 是一个指针? [英] In Go HTTP handlers, why is the ResponseWriter a value but the Request a pointer?

查看:22
本文介绍了在 Go HTTP 处理程序中,为什么 ResponseWriter 是一个值而 Request 是一个指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过为 GAE 编写应用程序来学习 Go,这是处理函数的签名:

I'm learning Go by writing an app for GAE, and this is signature of a handler function:

func handle(w http.ResponseWriter, r *http.Request) {}

我是指针新手,为什么 Request 对象是指针,而 ResponseWriter 不是?是否有必要采用这种方式,或者这只是为了使某种基于高级指针的代码成为可能?

I'm pointer newbie here, so why is the Request object a pointer, but the ResponseWriter not? Is there any need to have it this way or is this just to make some kind of advanced pointer based code possible?

推荐答案

你得到的 w 是一个指向非导出类型 http.response 的指针,但是作为 ResponseWriter 是一个接口,不可见.

What you get for w is a pointer to the non exported type http.response but as ResponseWriter is an interface, that's not visible.

来自 server.go:

type ResponseWriter interface {
    ...
}

另一方面,r 是指向具体结构的指针,因此需要显式传递引用.

On the other hand, r is a pointer to a concrete struct, hence the need to pass a reference explicitly.

来自 request.go:

type Request struct {
    ...
}

这篇关于在 Go HTTP 处理程序中,为什么 ResponseWriter 是一个值而 Request 是一个指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆