donseba / go-htmx

Seamless HTMX integration in golang applications

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Behavior of Handler.Write and Handler.WriteHeader is weird

ReneHollander opened this issue · comments

I can't make sense of the behavior of Handler.Write and Handler.WriteHeader and understand in which situation it is desireable.

Just calling Handler.WriteHeader doesn't actually write anything and just caches internal state. So if Handler.Write is not called, maybe because there are no data to write, headers are not written. (e.g imagine just sending a HX-Location without any data).

Also due to how Handler.Write behaves, if it's called multiple times, which is valid on any io.Writer, stdout is spammed with http: superfluous response.WriteHeader call from since the golang standard library complaints that WriteHeader has been called multiple times due to how this is implemented in this library:

// Write writes the data to the connection as part of an HTTP reply.
func (h *Handler) Write(data []byte) (n int, err error) {
	w := h.w

	for k, v := range h.response.Headers {
		w.Header().Set(k.String(), v)
	}

	w.WriteHeader(http.StatusOK)

	return w.Write(data)
}

// WriteHeader sets the response status
func (h *Handler) WriteHeader(code int) {
	if h.wroteHeader {
		return
	}

	h.statusCode = code
	h.wroteHeader = true
}

I think it would make a lot more sense to have Handler implement the golangs stdlib interface ResponseWriter to get reasonable behavior without confusion.

Hi, I'm really sorry for not catching this before. I will have a look and your argument makes a lot of sense. Give me 24 hours to check it and merge it in, if there are no obstacles.