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
180
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
What's context package
sivchari
June 13, 2024
More Decks by sivchari
See All by sivchari
govalid ~ Type-safe validation tool ~
sivchari
0
150
Go1.25 リリースパーティ ~ nil pointer bug ~
sivchari
0
140
Google Developer Group - DevFest Tokyo 2025
sivchari
0
150
Who tests the Tests ?
sivchari
0
180
Go 1.26 リリースパーティ
sivchari
0
220
静的解析 x Kubernetes API Conventions = Kube API Linter ~ ベストプラクティスに準拠したカスタムリソースの作り方と運用 ~
sivchari
0
220
What's GOCACHEPROG ?
sivchari
1
580
gh_extensionsによる快適なOSS生活.pdf
sivchari
0
180
Visualization Go scheduler by gosched-simulator
sivchari
1
670
Featured
See All Featured
Conquering PDFs: document understanding beyond plain text
inesmontani
PRO
4
2.9k
The untapped power of vector embeddings
frankvandijk
2
1.8k
Leadership Guide Workshop - DevTernity 2021
reverentgeek
1
320
Designing for Performance
lara
611
70k
Building a Modern Day E-commerce SEO Strategy
aleyda
45
9.1k
How to build a perfect <img>
jonoalderson
1
5.8k
How to Ace a Technical Interview
jacobian
281
24k
DBのスキルで生き残る技術 - AI時代におけるテーブル設計の勘所
soudai
PRO
67
56k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
35
3.6k
The Limits of Empathy - UXLibs8
cassininazir
1
480
Google's AI Overviews - The New Search
badams
0
1.1k
Exploring the relationship between traditional SERPs and Gen AI search
raygrieselhuber
PRO
2
4.1k
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が起きないか注意する