The database/sql package provides the possibility of canceling the pending statement. All the methods named XXXContext of DB struct pointer are the ones that consume the context, and it is possible to cancel the pending statement.
The canceling of the statement is possible only if the driver supports the Context variant. If it doesn't, the variant without the Context is executed.
With the Context variant and context.WithTimeout, you can create a timeout of the statement call.
Note that the sample code execution ends with the error pq: canceling statement due to user request, which corresponds with that of CancelFunc, which was called right after the query was executed.