Here is a beginner's question. Sorry that it's a bit long. I'd be happy
if somebody could help.
I am trying to turn an existing http.ResponseWriter into a new object, also
implementing the http.ResponseWriter interface. The new object should do
the following:
- in the WriteHeader method, set a session cookie before writing the header
- pass on everything else to the given parent ResponseWriter.
The following is a failed attempt to implement this:
--------------------------------------------------------------------------
type SessionResponseWriter struct {
http.ResponseWriter
SessionId []byte
}
func (w *SessionResponseWriter) WriteHeader(code int) {
setSessionCookie(w, w.SessionId, sessionTimeoutSeconds)
w.ResponseWriter.WriteHeader(code)
}
--------------------------------------------------------------------------
The above compiles, but does not work. The Write method seems to not call
my version of the WriteHeader method and thus the session cookie das not
get set if the user calls .Write().
I managed to fix the problem, using the following code:
--------------------------------------------------------------------------
type SessionResponseWriter struct {
parent http.ResponseWriter
wroteHeader bool
SessionId []byte
}
func (w *SessionResponseWriter) Header() http.Header {
return w.parent.Header()
}
func (w *SessionResponseWriter) Write(data []byte) (int, error) {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
n, err := w.parent.Write(data)
return n, err
}
func (w *SessionResponseWriter) WriteHeader(code int) {
w.wroteHeader = true
setSessionCookie(w.parent, w.SessionId, sessionTimeoutSeconds)
w.parent.WriteHeader(code)
}
--------------------------------------------------------------------------
This works, but looks ugly:
- The wroteHeader logic is now present both in w and in w.parent. This
looks like unnecessary duplication to me.
- The new Header() method doesn't do anything interesting. Do I really
need to write this out?
My question: Is there a better way of solving this problem?
Many thanks,
Jochen
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.