Golang: Ping succeeds a second time, even if the database is down

I had an interesting problem, namely that db.Ping () does not return an error, even if the database was killed on the first try.

Source code below:

import (
    "database/sql"
    "fmt"
    "log"
    "time"

    _ "github.com/go-sql-driver/mysql"
)

type database struct {
    datasource string
    conn       *sql.DB
}

// Connect creates and initialises a Database struct
func (db *database) Connect(server, user, password, DBPort string) error {
    var err error

    db.datasource = fmt.Sprintf("%s:%s@/", user, password)
    db.conn, err = sql.Open(server, db.datasource)
    if err != nil {
        log.Fatal(err)
    }

    err = db.conn.Ping()
    if err != nil {
        db.conn.Close()
        return err
    }

    log.Println("Waiting for 15 seconds, kill the DB")
    <-time.After(15 * time.Second)

    err = db.conn.Ping()
    if err != nil {
        db.conn.Close()
        return err
    }

    log.Println("Second ping successful")

    return nil
}

The database is completed first, so the first Ping completed successfully. However, I set the delay there for testing only. In 15 seconds I stop the database ( sudo service mysql stop), however db.Ping () is still successful.

If I made any actual request (via db.Query, db.QueryRowor db.Exec), then the sql package would panic with Broken Pipe (which is expected).

Am I doing something wrong?

also: go version go1.7.1 linux / amd64

Thanks in advance!

+6
source share
1

Ping . , , ( Go 1.8). , Ping , , .

Kardianos ( , Govendor) 1.8, . Ping , -.

+9

Source: https://habr.com/ru/post/1014026/


All Articles