Description

I need to close db connection before end of each end point, Is there a handler I can add to trigger when c.JSON, c.Abort been called

How to reproduce

Currently I workaround by at a LastHandler at each endpoint, but it not really look nice

server.GET("path1", EndpointHandler1, handlers.LastHandler)
server.GET("path2", EndpointHandler2, handlers.LastHandler)
server.GET("path3", EndpointHandler3, handlers.LastHandler)

Expectations

Able to add a handler in a single place, and this handler will trigger when response been fulfilled

Actual result

Need to add to each endpoint

Environment

  • go version: 1.19
  • operating system: ubuntu 22

Comment From: Gasoid

maybe you can use "defer"


func someFunc() {
  defer youFunc()
  .... other code


}

https://go.dev/tour/flowcontrol/12

Comment From: Gasoid

another point: "closing db connection" https://dba.stackexchange.com/questions/16969/how-costly-is-opening-and-closing-of-a-db-connection

you should consider to integrate db pool of connections or 1 persistent connection per app instance.

Comment From: hengway

@Gasoid thank you for the advice and suggest, I need to keep open db connection and close connection due to the service I do will need deal with multiple database base on client. And I only able to know which db to connect after the request happened.

I did tried out defer youFunc(), but I need to add this at the handler of each endpoint. But now I wish to do something that can centralize trigger when any response returned. Something similar to middleware, which can access the context as well.