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

前端 未结 5 1298
耶瑟儿~
耶瑟儿~ 2020-12-04 17:12

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) {}
5条回答
  •  执笔经年
    2020-12-04 17:50

    The reason why it’s a pointer to Request is simple: changes to Request by the handler need to be visible to the server, so we’re only passing it by reference instead of by value.

    If you dig into the net/http library code, you’ll find that ResponseWriter is an interface to a nonexported struct response, and we’re passing the struct by reference (we’re passing in a pointer to response) and not by value. ResponseWriter is an interface that a handler uses to create an HTTP response. The actual struct backing up ResponseWriter is the nonexported struct http.response. Because it’s nonexported, you can’t use it directly; you can only use it through the ResponseWriter interface.

    In other words, both the parameters are passed in by reference; it’s just that the method signature takes a ResponseWriter that’s an interface to a pointer to a struct, so it looks as if it’s passed in by value.

提交回复
热议问题