From 6629e77fd5eee461d77f3944130545bc251ab19e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=9A=E5=90=83=E7=82=B9=E8=8B=B9=E6=9E=9C?= <73388495+eatmoreapple@users.noreply.github.com> Date: Wed, 1 Feb 2023 23:54:11 +0800 Subject: [PATCH] =?UTF-8?q?[feat]:=20=E6=94=AF=E6=8C=81=E8=87=AA=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E6=B7=BB=E5=8A=A0=20context=20=E7=94=A8=E4=BA=8E?= =?UTF-8?q?=E6=8E=A7=E5=88=B6=20bot=20=E5=AD=98=E6=B4=BB=20(#220)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bot_login.go | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/bot_login.go b/bot_login.go index cb32127..0ae2568 100644 --- a/bot_login.go +++ b/bot_login.go @@ -1,6 +1,7 @@ package openwechat import ( + "context" "time" ) @@ -132,16 +133,16 @@ func NewSyncReloadDataLoginOption(duration time.Duration) BotLoginOption { return &SyncReloadDataLoginOption{SyncLoopDuration: duration} } -// WithModeOption 指定使用哪种客户端模式 -type WithModeOption struct { +// withModeOption 指定使用哪种客户端模式 +type withModeOption struct { mode Mode } // Prepare 实现了 BotLoginOption 接口 -func (w WithModeOption) Prepare(b *Bot) { b.Caller.Client.SetMode(w.mode) } +func (w withModeOption) Prepare(b *Bot) { b.Caller.Client.SetMode(w.mode) } func withMode(mode Mode) BotPreparer { - return WithModeOption{mode: mode} + return withModeOption{mode: mode} } // btw, 这两个变量已经变了4回了, 但是为了兼容以前的代码, 还是得想着法儿让用户无感知的更新 @@ -153,6 +154,19 @@ var ( Desktop = withMode(desktop) ) +// WithContextOption 指定一个 context.Context 用于Bot的生命周期 +type WithContextOption struct { + Ctx context.Context +} + +// Prepare 实现了 BotLoginOption 接口 +func (w WithContextOption) Prepare(b *Bot) { + if w.Ctx == nil { + panic("context is nil") + } + b.context, b.cancel = context.WithCancel(w.Ctx) +} + const ( defaultHotStorageSyncDuration = time.Minute * 5 )