Questions tagged [go-context]

In Go, a context is the main device to propagate deadlines and scoped values across APIs. Use this tag for questions related to context.Context type in Go, or third-party types that implement the Context interface.

Context is the preferred way in Go to carry request-scoped information across API boundaries, and between processes.

The package documentation recommends three main best practices when using context.Context, which are repeated here:

  • Context arguments should be passed as the first argument to functions that need it. This way is preferred to declaring context fields inside structs
  • context.TODO is to be used in place of a nil context
  • Context values should be used only for request-scoped values, and not to pass optional parameters to functions.
51 questions
8
votes
2 answers

context.TODO() or context.Background(), which one should I prefer?

I'm currently working on migrating our code from global sign package to go mongo-driver, not sure where should I use context.TODO() and context.Background(), it’s really confusing, I know both it returns non-nil empty, so should I use…
Gopher_k
  • 273
  • 2
  • 9
8
votes
1 answer

Why recommend ctx as the first parameter? Is stdlib really consistent about it?

As the documentation said Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it. The Context should be the first parameter, typically named ctx but I found, in the typical http request handle…
Neo Ko
  • 1,365
  • 15
  • 25
7
votes
1 answer

go-gin request cancellation

How do I cancel further processing if the connection is closed before 10 seconds? There is c.Request.Context().Done() but coudn't find an example on how to use it. func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { …
iamvinitk
  • 165
  • 3
  • 15
4
votes
2 answers

How to propagate context values from Gin middleware to gqlgen resolvers?

I am trying to extract user_id in token authentication middleware and pass it to gqlgen's graphql resolver function (to populate created_by and updated_by columns of GraphQL schema). Authentication part works without any problems. The Gin…
Helen Grey
  • 439
  • 6
  • 16
3
votes
1 answer

Passing data from handler to middleware after serving request

I have the following simple API in Go: package main import ( "context" "fmt" "net/http" "github.com/gorilla/mux" ) func middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r…
3
votes
1 answer

Error "(no value) used as value" from Go compiler using oklog/run

I am working on a simple example of oklog/run package, and am seeing this compilation error in VS Code when trying to return a log of the error: log.Errorf("abnormal termination: %s", err) (no value) used as value In the description of group.Run it…
Andrew Smith
  • 483
  • 1
  • 3
  • 16
3
votes
1 answer

Why golang g.cancel() is required in func (g *Group) Wait() error

golang's error group is very useful, below is the implementation func (g *Group) Go(f func() error) { g.wg.Add(1) go func() { defer g.wg.Done() if err := f(); err != nil { g.errOnce.Do(func() { g.err = err if…
Drake
  • 165
  • 1
  • 11
3
votes
1 answer

How can I pass a context.Context via Gin's context?

I'm trying to figure out the proper way to propagate a context.Context for the purposes of tracing with OpenTelemetry when using Gin. I currently have a gin handler that calls a function and passes a *gin.Context, like so: func (m Handler)…
Andrew DiNunzio
  • 143
  • 4
  • 17
3
votes
1 answer

Does Set() method of echo.Context saves the value to the underlying context.Context?

I am using Echo framework and want to pass the Go's built-in context.Context underlying echo.Context after setting some custom values. To achieve it, I think I could first apply Set(key string, val interface{}) method of echo.Context and then…
vahdet
  • 6,357
  • 9
  • 51
  • 106
3
votes
2 answers

Using context with cancel, Go routine doesn't terminate

I'm new to Go and concurrency in Go. I'm trying to use a Go context to cancel a set of Go routines once I find a member with a given ID. A Group stores a list of Clients, and each Client has a list of Members. I want to search in parallel all the…
aralk
  • 73
  • 6
3
votes
1 answer

Context value is nil when getting it with unexported struct key in Go HTTP handlers

Any help here is appreciated! I'm sure that I'm missing something really basic. The problem I have is I am trying to get a value out of context in a demo web application, and I'm receiving the error: 2021/04/11 11:35:54 http: panic serving…
ngriffin
  • 327
  • 4
  • 11
2
votes
1 answer

Reusing context.WithTimeout in deferred function

The below code snippet (reduced for brevity) from MongoDB's Go quickstart blog post creates context.WithTimeout at the time of connecting with the database and reuses the same for the deferred Disconnect function, which I think is buggy. func main()…
Aadithya V
  • 47
  • 8
2
votes
1 answer

When writing an http handler, do we have to listen for request context cancellation?

Supposed that I'm writing an http handler, that do something else before returning a response, do I have to setup a listener to check wether the http request context has been canceled? so that it can return immediately, or is there any other way to…
2
votes
1 answer

Can't use WithContext(ctx) method on *gorm.db instead of gorm.db

I initialize my db as a struct type DBStorage struct { db *gorm.DB } with db, err := gorm.Open("postgres", DatabaseURL) ... return &DBStorage{ db: db, } Everything works fine: queries, updates, and all other operations. But then I tried to…
2
votes
1 answer

Run function every N seconds with context timeout

I have a basic question about scheduling "cancellable" goroutines. I want to schedule a function execution, every 3 seconds. The function can take up to 5 seconds. In case it takes more than 2999ms I want to stop/terminate it, to avoid overlapping…
Fabio B.
  • 9,138
  • 25
  • 105
  • 177
1
2 3 4