Open4

完全に理解したと思ってたgoが何もわからなくなってきたので色々読むます

おすしおすし

Context is何

https://zenn.dev/hsaki/books/golang-context/viewer/definition

https://medium.com/@agatan/httpサーバとcontext-context-7211433d11e6

http.Request は func(*Request) Context() context.Context というメソッドを持っています

https://www.sohamkamani.com/golang/context-cancellation-and-values/

There are two sides to context cancellation:
Listening for the cancellation event
Emitting the cancellation event

If you have an operation that could be cancelled, you will have to emit a cancellation event through the context.

ctx, fn := context.WithCancel(ctx)
This function takes no arguments, and does not return anything, and is called when you want to cancel the context.

Unless this is explicitly what you want, you should always create a new context when running a function in a different goroutine, like so:

bad example

func doSomething() {
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	someArg := "loremipsum"
	go doSomethingElse(ctx, someArg)
}

good example

func doSomething() {
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	someArg := "loremipsum"
	go doSomethingElse(context.Background(), someArg)
}

The most important of which, is that a context can only be cancelled once.

The most idiomatic way to use cancellation is when you actually want to cancel something, and not just notify downstream processes that an error has occurred.

https://www.wakuwakubank.com/posts/867-go-context/

<-ctx.Done() でキャンセル関数の実行を検知できます。