Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing http.ResponseWriter by value or reference?

Tags:

go

Assume I'm having a central method which adds a specific header to the http.ResponseWriter. I don't want to use a HandleFunc wrapper.

I wonder, whether I'd send in the ResponseWriter by reference. So, what would be correct:

addHeaders(&w)

or

addHeaders(w)

Asked differently:

func addHeaders(w *http.ResponseWriter) {...}

or

func addHeaders(w http.ResponseWriter) {...}

From my understanding, I'd say the first version would be correct, as I don't want to create a copy of ResponseWriter. But I haven't seen any code where ResponseWriter is passed by reference and wonder why.

Thanks!

like image 453
Ralf Avatar asked Mar 03 '14 21:03

Ralf


1 Answers

http.ResponseWriter is an interface. You want to pass its value, since it internally contains a pointer to the actual Writer. You almost never want a pointer to an interface.

Look at what a standard handler func's signature is:

func(http.ResponseWriter, *http.Request)

Notice that ResponseWriter isn't a pointer.

like image 102
JimB Avatar answered Oct 07 '22 18:10

JimB