Search⌘ K
AI Features

Common Network Utilities

Explore how to make HTTP calls effectively in Go by implementing context-based cancellation and measuring API response times. Understand how to gain full control over network interactions and monitor dependency performance to maintain service reliability and scalability.

Armed with a solid understanding of what APIs are and how we can optimize our interactions with them, we are in a reliable place to start making HTTP calls to resolve our dependencies. Let’s make two final additions to our arsenal to get complete control and insights into our network calls.

Canceling with context

Following the trend of ensuring we get fine-grained control over how long we spend on a single API interaction, let’s see if we can actively cancel or abort a network call proactively based on our logic.

Go (1.18.2)
func getTimedContext(timeout int) (*context.Context, *time.Timer) {
ctx, cancel := context.WithCancel(context.TODO())
timer := time.AfterFunc(time.Duration(timeout)*time.Second, func() {
cancel()
})
return &ctx, timer
}

The getTimedContext function will return ...