gogo-context

Best way to pass context


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.


Solution

  • 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.