Best way to pass context

6.7k views Asked by At

I've done a lot of research regarding context, but I can't seem to find a generally accepted answer, plus I'm new to Go.

In my current code I've var ctx = context.Background(),which is used in various places.

My concern is, aren't all my code modifying the same context since it's a global variable? .

Yes, I know context is request scoped.

This is part of my code for context.

var ctx = context.Background()

var db *firestore.Client

var auth *aut.Client

func init() {
    app, err := firebase.NewApp(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }
    db, err = app.Firestore(ctx)
    if err != nil {
        log.Fatal(err)
    }
    auth, err = app.Auth(ctx)
    if err != nil {
        log.Fatal(err)
    }
}

func SetRate(r int) (err error) {
    //TODO: create last updated field
    _, err = db.Collection("Rate").Doc("rate").Set(ctx, map[string]int{"USDT": r})
    if err != nil {
        log.Println(err)
        return err
    }
    return nil
}

Please try not to use overly complicated words to describe a term.

2

There are 2 answers

2
Em Ae On BEST ANSWER

Its an accepted practice in go to pass context from function to function. Normally, the first parameter of every function if context type. I have seen that whenever a context is passed down and has some use-case with in the method scope, a new context is created from parent context.

0
Grehgous On

It is best practice to create a context inside of a function and pass it between functions as needed, rather than having the one context shared across the package. For something like a HTTP server, you will typically see a unique context for each incoming API call.