Go の公式ブログ「Contexts and structs」では、context は構造体のフィールドに保持せず、関数やメソッドの第一引数として渡すことが推奨されています。構造体に context を保持すると、リクエストのライフサイクルと構造体のライフサイクルが混同され、キャンセル伝播やタイムアウトが意図通りに動作しなくなります。
// 1. サービス層に context を保持 type OrderService struct { ctx context.Context // found a struct that contains a context.Context field db *sql.DB logger *slog.Logger }
// 2. ハンドラーに context を保持 type Handler struct { ctx context.Context // found a struct that contains a context.Context field svc *Service }
// 3. 埋め込みではないが context.Context 型のフィールド type Worker struct { parentCtx context.Context // found a struct that contains a context.Context field tasks chan Task }