GOLANG PACKAGE

Understanding the context package

Communication between goroutines can be troublesome at times using channels as the only communication medium. In this article, we are going to look at the context package to send cancellation signals between API boundaries.

Uday Hiwarale
May 6, 2020 · 9 min read
Image for post
Image for post
(source: unsplash.com)
Image for post
Image for post
(https://play.golang.org/p/weqWhW-RoGB)
Image for post
Image for post
(https://play.golang.org/p/orgAz9P4d9E)
type Context interface {
Deadline() (deadline time.Time, ok bool)
Done() <-chan struct{}
Err() error
Value(key interface{}) interface{}
}

context.Background()

context.WithCancel

func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
Image for post
Image for post
(https://play.golang.org/p/24NF68Nbl_T)
Image for post
Image for post
((https://play.golang.org/p/CjDfFsHWttl))

context.WithDeadline

func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)
Image for post
Image for post
(https://play.golang.org/p/2RQ9sC1nbIB)

context.WithTimeout

func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
func WithTimeout(p Context, t time.Duration) (Context, CancelFunc) {
return WithDeadline(p, time.Now().Add(t))
}
Image for post
Image for post

RunGo

A go-to guide for learning Go programming language

Uday Hiwarale

Written by

Senior Software Engineer (JS • Go • Dart • Python) / Available for full-time role / thatisuday.com ☯ github.com/thatisuday ☯ thatisuday@gmail.com

RunGo

RunGo

A place to find introductory Go programming language tutorials and learning resources. In this publication, we will learn Go in an incremental manner, starting from beginner lessons with mini examples to more advanced lessons.

Uday Hiwarale

Written by

Senior Software Engineer (JS • Go • Dart • Python) / Available for full-time role / thatisuday.com ☯ github.com/thatisuday ☯ thatisuday@gmail.com

RunGo

RunGo

A place to find introductory Go programming language tutorials and learning resources. In this publication, we will learn Go in an incremental manner, starting from beginner lessons with mini examples to more advanced lessons.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store