DB.PingContext in Go

Posted by GoDoc
Public (Editable by Users)

PingContext verifies a connection to the database is still alive, establishing a connection if necessary.

Go
Edit
package main

import (
	"context"
	"log"
	"time"
)

func main() {
	// Ping and PingContext may be used to determine if communication with
	// the database server is still possible.
	//
	// When used in a command line application Ping may be used to establish
	// that further queries are possible; that the provided DSN is valid.
	//
	// When used in long running service Ping may be part of the health
	// checking system.

	ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
	defer cancel()

	status := "up"
	if err := db.PingContext(ctx); err != nil {
		status = "down"
	}
	log.Println(status)
}