Suppose I have a method of type http.HandleFunc
type HandlerFunc func(ResponseWriter, *Request)
And I want to wrap it around another method of the same type, somewhat like this:
func MyWrapper(res http.ResponseWriter, req *http.Request) {
// do stuff
AnotherMethod(res, req) // <- question refers to this line
// do more stuff
}
func AnotherMethod(res http.ResponseWriter, req *http.Request) {
// main logic
}
If I'm getting this right; when I call AnotherMethod(res, req)
I'm passing a copy of (the value of) res
to AnotherMethod
, meaning that this object is now duplicated in memory.
Is there a way I could pass a pointer to res
to AnotherMethod
and then dereference there, in order to not copy the value of res
? or am I not understanding something?
(Working with a pointer to (the value of) res
inside AnotherMethod
won't work because the receivers of all methods in http.ResponseWriter
are values and not pointers)
http.ResponseWriter
is an interface type. Which means it can be both a reference or value type, depending on what the underlying type is and how it implements the interface.
In this case, res
is an instance of the unexported type *http.response
. As you can see, it is a pointer type, which means you can pass it around without creating a copy of the whole structure.
To see what real type is held inside an interface value you are receiving, you can do this: fmt.Printf("%T ", res)
. It should print: *http.resonse
.
For more information on how interface types work in Go, I recommend reading the Go specification on the subject.