Get the App
SLTechnology News&Howtos  ›  Development  › 

The function and Operation method of context package in go language

Shulou Source: shulou.com Published: 2022-05-31 22:15:37 09月14日 Update

This article introduces the knowledge of "the function and operation of the context package of go language". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

What on earth is the Context bag for?

We will see the shadow of context when we use a lot of things, such as gin framework, such as grpc, what exactly does this thing do?

Everyone is using it, and few of them know what it is, but they don't know why.

The principle is to put it bluntly:

The current protocol has been cancelled. You can notify all subprograms created by it to exit.

The current protocol has been cancelled and will not affect the state of the parent program that created it

Extended additional functions: timeout cancellation, timing cancellation, and data sharing with subprograms

Context principle

This is the core principle of context package, passing context in chain and constructing new context based on context.

When should I use Context?

Every RPC call should have the ability to time out, which is a reasonable API design.

Not only do you time out, but you also need the ability to end behaviors that no longer need to be operated.

Context.Context is the solution of Go standard

Any function that may be blocked or takes a long time to complete should have a context.Context

How do I create a Context?

At the beginning of RPC, use context.Background ()

Some people record a context.Background () in main (), put this in a variable on the server, and then inherit context from that variable after the request comes. It's not right to do this. Each request directly originates from its own context.Background ().

If you don't have context but need to call a function of context, use context.TODO ()

If a step requires its own timeout setting, give it a separate sub-context (as in the previous example)

The main co-program notifies a sub-coprogram, and the sub-co-program has multiple sub-coprograms package mainimport ("context"fmt"time") func main () {ctx, cancel: = context.WithCancel (context.Background ()) / / buffer channel pre-places 10 messages messages: = make (chan int, 10) defer close (messages) for I: = 0; I < 10; iSync + {messages

Tags: Time method principle node task core message structure result storage function layer 2 signal information content function variable that is channel Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology OPPO Reno Huawei Xiaomi vpn