Timeouts for popular Go packages

Go Timeouts

An unresponsive service can be worse than a down one. It can tie up your entire system if not handled properly. All network requests should have a timeout.

Here’s how to add timeouts for popular Go packages. All have been tested. The default is no timeout, unless otherwise specified. Enjoy!

Build Status

Packages

Standard library

github.com

Other

Standard Library

net

conn, err := net.DialTimeout(network, address, time.Second)
if err != nil {
    // handle error
}
err = conn.SetDeadline(time.Now().Add(time.Second))

net/http

client := http.Client{
    Timeout: time.Second,
}

net/smtp

conn, err := net.DialTimeout("tcp", address, time.Second)
if err != nil {
    // handle error
}
err = conn.SetDeadline(time.Now().Add(time.Second))
if err != nil {
    // handle error
}
client, err = smtp.NewClient(conn, host)

os/exec

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
err := exec.CommandContext(ctx, cmd).Run()

github.com

aws/aws-sdk-go

sess := session.Must(session.NewSession(&aws.Config{
    HTTPClient: &http.Client{Timeout: time.Second},
}))

aws/aws-sdk-go-v2

cfg, err := config.LoadDefaultConfig(context.TODO(),
    config.WithHTTPClient(&http.Client{Timeout: time.Second}),
)

bradfitz/gomemcache

mc := memcache.New(host)
mc.Timeout = time.Second

couchbase/gocb

cluster, err := gocb.Connect(connStr, gocb.ClusterOptions{
    TimeoutsConfig: gocb.TimeoutsConfig{
        ConnectTimeout:    time.Second,
        KVTimeout:         time.Second,
        ViewTimeout:       time.Second,
        QueryTimeout:      time.Second,
        AnalyticsTimeout:  time.Second,
        SearchTimeout:     time.Second,
        ManagementTimeout: time.Second,
    },
})

See the docs for defaults

elastic/go-elasticsearch

cfg := elasticsearch.Config{
    Transport: &http.Transport{
        DialContext: (&net.Dialer{
            Timeout: time.Second,
        }).DialContext,
        ResponseHeaderTimeout: time.Second,
    },
}
es, err := elasticsearch.NewClient(cfg)

emersion/go-smtp

conn, err := net.DialTimeout("tcp", address, time.Second)
if err != nil {
    // handle error
}
err = conn.SetDeadline(time.Now().Add(time.Second))
if err != nil {
    // handle error
}
client, err = smtp.NewClient(conn, host)

gocql/gocql

cluster := gocql.NewCluster(host)
cluster.ConnectTimeout = time.Second
cluster.Timeout = time.Second

Default: 600ms connect timeout, 600ms read timeout

go-pg/pg

db := pg.Connect(&pg.Options{
    DialTimeout:  time.Second,
    ReadTimeout:  time.Second,
    WriteTimeout: time.Second,
})

go-redis/redis

rdb := redis.NewClient(&redis.Options{
    DialTimeout:  time.Second,
    ReadTimeout:  time.Second,
    WriteTimeout: time.Second,
})

go-sql-driver/mysql

cfg := mysql.Config{
    Timeout:      time.Second,
    ReadTimeout:  time.Second,
    WriteTimeout: time.Second,
}
db, err := sql.Open("mysql", cfg.FormatDSN())

opensearch-project/opensearch-go

cfg := opensearch.Config{
    Transport: &http.Transport{
        DialContext: (&net.Dialer{
            Timeout: time.Second,
        }).DialContext,
        ResponseHeaderTimeout: time.Second,
    },
}
client, err := opensearch.NewClient(cfg)

Other

go.mongodb.org/mongo-driver/mongo

ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))

Don’t see a library you use?

Let us know. Even better, create a pull request for it.

Running the Tests

git clone https://github.com/ankane/go-timeouts.git
cd go-timeouts
go mod tidy

To run all tests, use:

go test ./... -v

To run individual tests, use:

go test test/helper_test.go test/net_http_test.go -v
Similar Resources

A corpus of popular Go modules

corpus A corpus of popular Go modules. See top-100.tsv for the latest sample. This corpus is to be used when analyzing or studying Go code.

Jan 6, 2023

🐳 A most popular sql audit platform for mysql

🐳 A most popular sql audit platform for mysql

🐳 A most popular sql audit platform for mysql

Jan 6, 2023

An implementation of the popular game Codenames created with Go and React.

OpenCodenames A real-time implementation of Codenames created with React/TypeScript and Golang. You can play the game here! Installation Stack: React

Aug 8, 2021

A collection of 100+ popular LeetCode problems solved in Go.

go-leetcode A collection of 100+ popular LeetCode problems that I've solved in Go. Each directory includes a: Description with link to LeetCode proble

Dec 25, 2022

fim is a collection of some popular frequent itemset mining algorithms implemented in Go.

fim fim is a collection of some popular frequent itemset mining algorithms implemented in Go. fim contains the implementations of the following algori

Jul 14, 2022

A simple server which can be used as an RPC endpoint in popular Ethereum wallets.

RPC Endpoint This repository contains code for a simple server which can be used as an RPC endpoint in popular Ethereum wallets. The endpoint is https

Jan 2, 2023

Package implement reading and writing popular playlist formats: PLS, ASX, M3U, XSPF and others.

go-playlist ⚠️ WARNING The API is not stable yet and can change. Package playlist implement reading and writing popular playlist formats: PLS, ASX, M3

Oct 14, 2021

Just Dance Unlimited mock-up server written on Golang and uses a popular Gin framework for Go.

BDCS Just Dance Unlimited mock-up server written on Golang and uses a popular Gin framework for Go. Features Security Authorization works using UbiSer

Nov 10, 2021

Go serverless functions examples with most popular Cloud Providers

go-serverless Go serverless functions examples with most popular Cloud Providers Creating zip archive go mod download go build ./cmd/aws|gcp zip -

Nov 16, 2021

Vale-compatible implementations of many popular "readability" metrics.

Readability This repository contains a Vale-compatible implementation of many popular "readability" metrics. Getting Started ❗ Readability requires Va

Aug 31, 2022

Examples of using various popular database libraries and ORM in Go.

Introduction Examples of using various popular database libraries and ORM in Go. sqlx sqlc Gorm sqlboiler ent The aim is to demonstrate and compare us

Dec 12, 2021

Examples of using various popular database libraries and ORM in Go.

Introduction Examples of using various popular database libraries and ORM in Go. sqlx sqlc Gorm sqlboiler ent The aim is to demonstrate and compare us

Dec 28, 2022

Go-fastapi: a library to quickly build APIs. It is inspired by Python's popular FastAPI

Go-fastapi: a library to quickly build APIs. It is inspired by Python's popular FastAPI

go-fastapi go-fastapi is a library to quickly build APIs. It is inspired by Pyth

Jan 1, 2023

Implementation of a popular graphics benchmark written on Ebiten.

Implementation of a popular graphics benchmark written on Ebiten.

Ebiten Bunny Mark This is an implementation of the popular graphics benchmark written on Ebiten. The initial benchmark was created by Ian Lobb (code)

Dec 7, 2022

A TUI implementation of the popular word quiz wordle!

gordle A TUI implementation of the popular word quiz Wordle! Building Build the cli command: $ go build ./cmd/cli Empty output on build success Buil

Dec 21, 2022

WordleSolver - A solver for the popular word game Wordle

WordleSolver This is a solver for the popular word game Wordle. How to use the s

Jan 28, 2022

Gocaptcha - An API wrapper for popular captcha solvers such as AntiCaptcha and 2Captcha in Golang

An API wrapper for popular captcha solvers such as AntiCaptcha and 2Captcha in Golang

Nov 1, 2022

Gin-errorhandling - Gin Error Handling Middleware is a middleware for the popular Gin framework

Gin Error Handling Middleware Gin Error Handling Middleware is a middleware for

Sep 19, 2022

Package goth provides a simple, clean, and idiomatic way to write authentication packages for Go web applications.

Goth: Multi-Provider Authentication for Go Package goth provides a simple, clean, and idiomatic way to write authentication packages for Go web applic

Dec 29, 2022
Related tags
A simple server which can be used as an RPC endpoint in popular Ethereum wallets.

RPC Endpoint This repository contains code for a simple server which can be used as an RPC endpoint in popular Ethereum wallets. The endpoint is https

Jan 2, 2023
gophertunnel is composed of several packages that may be of use for creating Minecraft related tools
gophertunnel is composed of several packages that may be of use for creating Minecraft related tools

gophertunnel is composed of several packages that may be of use for creating Minecraft related tools. A brief overview of all packages may be found here.

Dec 31, 2022
The repository provides supplementary Go time packages

Go Time This repository provides supplementary Go time packages. Download/Install The easiest way to install is to run go get -u golang.org/x/time. Yo

Nov 23, 2021
Tools - This subrepository holds the source for various packages and tools that support

Go Tools This subrepository holds the source for various packages and tools that

Jan 12, 2022
a Go HTTP client with timeouts

go-httpclient requires Go 1.1+ as of v0.4.0 the API has been completely re-written for Go 1.1 (for a Go 1.0.x compatible release see 1adef50) Provides

Nov 10, 2022
go HTTP client that makes it plain simple to configure TLS, basic auth, retries on specific errors, keep-alive connections, logging, timeouts etc.

goat Goat, is an HTTP client built on top of a standard Go http package, that is extremely easy to configure; no googling required. The idea is simila

Jun 25, 2022
Simple Go program to prevent AFK timeouts during FFXIV Endwalker launch.
Simple Go program to prevent AFK timeouts during FFXIV Endwalker launch.

Idler Just a super simple keyboard idler written in Go, to assist in hands-free queueing/preventing AFK timeouts during the FFXIV Endwalker expansion

Dec 22, 2021
Go program that fetches URLs concurrently and handles timeouts

fetchalltimeout This is an exercise of the book The Go Programming Language, by

Dec 18, 2021
Client tool for testing HTTP server timeouts

HTTP timeout test client While testing Go HTTP server timeouts I wrote this little tool to help me test. It allows for slowing down header write and b

Sep 21, 2022
Test your code without writing mocks with ephemeral Docker containers 📦 Setup popular services with just a couple lines of code ⏱️ No bash, no yaml, only code 💻

Gnomock – tests without mocks ??️ Spin up entire dependency stack ?? Setup initial dependency state – easily! ?? Test against actual, close to product

Dec 29, 2022