// create a new context object ctx := context.Background() // set a value in the context ctx = context.WithValue(ctx, "user-id", 123) // pass the context to a handler function handlerFunc(ctx)
func handlerFunc(ctx context.Context) { // get the user-id value from the context userID, ok := ctx.Value("user-id").(int) if !ok { // handle error } // continue with the handler logic }
// create a new context object ctx := context.Background() // create a struct to hold JSON data type Data struct { Name string `json:"name"` Age int `json:"age"` } // unmarshal JSON into struct jsonData := []byte(`{"name":"Alice", "age":30}`) var data Data err := json.Unmarshal(jsonData, &data) if err != nil { // handle error } // set the struct in the context ctx = context.WithValue(ctx, "json-data", data) // marshal the struct back to JSON jsonData, err = json.Marshal(data) if err != nil { // handle error } // pass the context to a handler function handlerFunc(ctx)In this example, we create a new context object and use `json.Unmarshal()` to convert some JSON data into a struct. We then use `context.WithValue()` to store the struct in the context. Finally, we use `json.Marshal()` to convert the struct back to JSON and pass the context to a handler function. The package library is "github.com/gogits/gogs/modules/context".