Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Go HTTP handlers, why is the ResponseWriter a value but the Request a pointer?

Tags:

pointers

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

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?

like image 297
Sudhir Jonathan Avatar asked Nov 06 '12 17:11

Sudhir Jonathan


People also ask

Why HTTP request is a pointer?

Several methods on http. Request modify the request thus require a pointer receiver thus requests are handled around as pointers everywhere. This is called consistency and has nothing to do with syntactic sugar or readability.

What is HTTP handler go?

Strictly speaking, what we mean by handler is an object which satisfies the http.Handler interface: type Handler interface { ServeHTTP(ResponseWriter, *Request) } In simple terms, this basically means that to be a handler an object must have a ServeHTTP() method with the exact signature: ServeHTTP(http.


1 Answers

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.

From server.go:

type ResponseWriter interface {     ... } 

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

From request.go:

type Request struct {     ... } 
like image 50
Denys Séguret Avatar answered Sep 19 '22 18:09

Denys Séguret