Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
What's context package
Search
sivchari
June 13, 2024
140
0
Share
What's context package
sivchari
June 13, 2024
More Decks by sivchari
See All by sivchari
govalid ~ Type-safe validation tool ~
sivchari
0
99
Go1.25 リリースパーティ ~ nil pointer bug ~
sivchari
0
98
Google Developer Group - DevFest Tokyo 2025
sivchari
0
99
Who tests the Tests ?
sivchari
0
110
Go 1.26 リリースパーティ
sivchari
0
170
静的解析 x Kubernetes API Conventions = Kube API Linter ~ ベストプラクティスに準拠したカスタムリソースの作り方と運用 ~
sivchari
0
170
What's GOCACHEPROG ?
sivchari
1
530
gh_extensionsによる快適なOSS生活.pdf
sivchari
0
130
Visualization Go scheduler by gosched-simulator
sivchari
1
600
Featured
See All Featured
Everyday Curiosity
cassininazir
0
200
Designing Experiences People Love
moore
143
24k
Darren the Foodie - Storyboard
khoart
PRO
3
3.3k
The B2B funnel & how to create a winning content strategy
katarinadahlin
PRO
1
340
Effective software design: The role of men in debugging patriarchy in IT @ Voxxed Days AMS
baasie
0
310
Crafting Experiences
bethany
1
120
A Tale of Four Properties
chriscoyier
163
24k
Self-Hosted WebAssembly Runtime for Runtime-Neutral Checkpoint/Restore in Edge–Cloud Continuum
chikuwait
0
500
Navigating Algorithm Shifts & AI Overviews - #SMXNext
aleyda
1
1.2k
Pawsitive SEO: Lessons from My Dog (and Many Mistakes) on Thriving as a Consultant in the Age of AI
davidcarrasco
0
120
SERP Conf. Vienna - Web Accessibility: Optimizing for Inclusivity and SEO
sarafernandez
2
1.4k
The Illustrated Children's Guide to Kubernetes
chrisshort
51
52k
Transcript
What’s context package ? sivchari
context package contextパッケージの中で定義されているContext型は、デッドライン、キャンセルシグナ ル、その他のリクエストに応じた値をAPI境界やプロセス間で伝達します FYI context
ex ListenAndServeはリクエストごとにgoroutineを 生成する 実践的に考えるとそれぞれの goroutineがさら にgoroutineを生成する可能性がある (DB, 外部APIへのリクエスト) -> 意識せず多くのgoroutineを生成している可
能性がある -> goroutineは勝手に消滅する? -> goroutine leak
goroutine leak out put 1 before 2 in leak 2
after leak この場合はnil chanをしっかりmakeしてcloseまでする必 要がある nilでもchannelはcompile timeでerrorを発見できない(可 能性としてはruntime error)
problem - goroutine leakがより複雑になり10個などになった時 - タイムアウトした時 - 使っているライブラリでgoroutineが生成されていたら? - ある関数はcloseしたいが、ある関数は継続させたい処理にどう対応する?
- チャネルを複数用意する方法もあるがチャネルの生成にはコストがかかる
context context.Contextはinterface BackgroundやWithCancelなどユースケースによる実 装をinterfaceで抽象化できる しない場合 context.WithCancelなど限定的な型が必要
Background contextの生成にはBackgroundを使う 内部実装はContext interfaceを満たすprivate pointer intが生成される contextを使うか微妙な場合はcontext.TODOを引数に取る
contextの関係 - contextが親子関係にある - 親のcontextのキャンセルは親から派生したcontextも同じ挙動をとる - contextが兄弟関係にある(parentからctx1, ctx2が生成される) - 親がキャンセルされるとどちらも終了する
- 言い換えると親は子の影響を受けない - ある関数はcloseしたいが、ある関数は継続させたい処理にどう対応する?という 問題が解決される
Request Scope of context Keyを指定してcontextにセットする 同じcontextに対してkeyでsetした値を取得する type structの理由は一意性を型として担保するため ex) 別packageごとに同じkeyをセットした場合を考える
(hogeとfugaで同じ文字列をkeyにする) パッケージに閉じた(privateな)keyを使うようにする Q. 閉じていればintなどでもいいのでは? - 空のstructはメモリサイズが0 FYI https://go.dev/play/p/TYZV5GPrIWm
Don’t use context like this structの中にcontextを含めない - contextにはスコープごとの値がsetされるかもしれない(JWT, Token etc..)
- structに含めるとどこで参照されるかわからない 実際にBad PracticeとGo Teamが言っている Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions. context -> 第一引数で渡すようにする
Why? - スコープがinterface(API)として明確になる - 例外はnet/http - 後方互換性(contextは1.7から登場した) - database/sqlはcontext対応のメソッドを生やした FYI
https://go.dev/blog/context-and-structs https://github.com/golang/go/blob/ecf6b52b7f4ba6e8c98f25adf9e83773fe908829/ src/net/http/request.go#L319-L323
まとめ - 自分のライブラリを作る場合はcontextを渡すようなinterfaceを実装する - クライアント(使う側)から明示的にストップさせる以外はcontextを使う方がいい (streamなどはchannelを使う方がいい) - 逆説としてchannelを使うときはgoroutine leakが起きないか注意する