Golang context.WithValue: how to add several key-value pairs

后端 未结 5 1056
一生所求
一生所求 2020-12-24 11:24

With Go\'s context package it is possible to pass request-specific data to the stack of request handling functions using

func WithValue(parent C         


        
5条回答
  •  萌比男神i
    2020-12-24 12:09

    As "icza" said you can group the values in one struct:

    type vars struct {
        lock    sync.Mutex
        db      *sql.DB
    }
    

    Then you can add this struct in context:

    ctx := context.WithValue(context.Background(), "values", vars{lock: mylock, db: mydb})
    

    And you can retrieve it:

    ctxVars, ok := r.Context().Value("values").(vars)
    if !ok {
        log.Println(err)
        return err
    }
    db := ctxVars.db
    lock := ctxVars.lock
    

提交回复
热议问题