logo
  • 現在做什麼
  • 關於我

Kalan

文章分類

  • 前端
  • 開發筆記
  • 雜談
  • 年度回顧

快速連結

  • 現在做什麼
  • 關於我
  • 聯絡我
  • 職涯思考🔗

關注我

在福岡生活的開發者,分享軟體開發與日本生活的點點滴滴。

© 2025 Kalan Made with ❤️. All rights reserved.

How to handle connection lost in Go?

Written byKalanKalanJan 15, 2019
Home/Dev Note
💡

If you have any questions or feedback, pleasefill out this form

Japanese原文

Table of Contents

    This post is translated by ChatGPT and originally written in Mandarin, so there may be some inaccuracies or mistakes.

    I researched some of the currently popular sql packages and found that almost none of them have a feature that throws an error immediately when a connection is lost. For example, in nodejs with MySQL, we can listen for errors using connection.on('error').

    However, in Golang (at least in several popular packages), there isn't a similar feature available. Upon further investigation, it's not hard to understand why.

    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; instead, it maintains a connection pool internally and only attempts to connect when necessary. This means that if you lose a connection due to network issues while executing a query, database/sql will attempt to retry for you at the lower level.

    On the bright side, this is a good thing, as it saves you from having to handle the retry logic yourself. However, sometimes you might prefer to be aware of a lost connection before executing a query, so that the entire application knows about the issue in advance.

    If you want to achieve similar functionality, you will need to rewrite the underlying Dialer logic to ensure that your application is notified immediately when a network disconnection occurs.

    ← [golang notes] How to set environment variables for your projectDealings with cookies with CORS →

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

    ☕Buy me a coffee