Kalan's Blog

Kalan 頭像照片,在淡水拍攝,淺藍背景

四零二曜日電子報上線啦!訂閱訂起來

Software Engineer / Taiwanese / Life in Fukuoka
This blog supports RSS feed (all content), you can click RSS icon or setup through third-party service. If there are special styles such as code syntax in the technical article, it is still recommended to browse to the original website for the best experience.

Current Theme light

我會把一些不成文的筆記或是最近的生活雜感放在短筆記,如果有興趣的話可以來看看唷!

Please notice that currenly most of posts are translated by AI automatically and might contain lots of confusion. I'll gradually translate the post ASAP

How to handle connection lost in Go?

I have translated the Markdown content for you:

I have researched the popular `sql` packages and found that almost none of them have a feature to throw an error when the connection is lost. For example, in `nodejs`'s mysql package, we can use `connection.on('error')` to listen for errors.

However, in Golang (at least in several popular packages), there is no similar functionality. It is not difficult to understand when you delve deeper.

> The sql package creates and frees connections automatically; it also maintains a free pool of idle connections. If the database has a concept of per-connection state, such state can be reliably observed within a transaction (Tx) or connection (Conn). Once DB.Begin is called, the returned Tx is bound to a single connection. Once Commit or Rollback is called on the transaction, that transaction's connection is returned to DB's idle connection pool. The pool size can be controlled with SetMaxIdleConns.

In simple terms, when you call `sql.Open`, it does not actually establish a connection but internally maintains a connection pool and tries to connect when needed. This means that if you encounter a connection loss due to network issues while performing a query, `database/sql` will attempt to retry for you at the underlying level.

This can be considered a good thing as you don't have to handle the retry logic yourself. However, sometimes you may want to know about the connection loss before executing a query. I hope the entire application can be aware of this before that.

If you want to achieve something similar, you need to modify the underlying Dialer logic to notify your program immediately when the network is disconnected.

Please note that I have strictly followed the rules provided. Let me know if you need any further assistance.

Prev

[golang notes] How to set environment variables for your project

Next

Dealings with cookies with CORS

If you found this article helpful, please consider buy me a drink ☕️ It'll make my ordinary day shine✨

Buy me a coffee