V
V
veryoriginalnickname2021-09-23 20:04:29
go
veryoriginalnickname, 2021-09-23 20:04:29

How to check if a response has been sent before and where to add this check?

There is a router ( code here ). You can add global middleware to the router, for all paths, and individual ones.
The problem is this: let's say if the user adds 2 global middleware, and in the first middleware sends a response

writer.WriteHeader(403)
writer.Write([]byte("что-то"))

then in the second middleware, or already in the controller, when the response is resent, it will be
http: superfluous response.WriteHeader call
How to make each middleware check if the response was sent before? If the response was sent before, then a return will occur, and the request processing will end.
BUT there is a problem here. Even if you find out if a response was sent before, the question arises: where should this check be? It comes to mind to make some kind of hook that will be called every time the next middleware is called, but this is not an option, because when the router is initialized, a thing is called that does something like one big middleware
func middlewareChainer(middlewares []TheMiddleware, next http.Handler) http.Handler {
  for i := len(middlewares) - 1; i >= 0; i-- {
    next = middlewares[i](next)
  }
  return next
}

I don’t really want to remove this thing, because if you remove it, you will have to sort through the slice with middleware with each request, which is not cool at all.

Total:
1. How do I know if a response has been sent before?
2. Where can I file this check?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Shitskov, 2021-09-23
@veryoriginalnickname

If the Middleware has written the headers and the response, it should call return, not next

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question