From 76bd0a56485c4d791b2aa6579d7c67ede5d50d20 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:43:10 +0800 Subject: [PATCH] =?UTF-8?q?[fix]:=20=E8=A7=A3=E5=86=B3=E5=AE=9A=E6=97=B6?= =?UTF-8?q?=E5=99=A8=E5=90=8C=E6=AD=A5=E6=95=B0=E6=8D=AE=E5=88=B0=E7=83=AD?= =?UTF-8?q?=E5=AD=98=E5=82=A8=E4=B8=AD=E7=9A=84=E6=95=B0=E6=8D=AE=E7=AB=9E?= =?UTF-8?q?=E4=BA=89=E9=97=AE=E9=A2=98=20https://github.com/eatmoreapple/o?= =?UTF-8?q?penwech=E2=80=A6=20(#219)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- stroage.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/stroage.go b/stroage.go index fe18795..b9ffd97 100644 --- a/stroage.go +++ b/stroage.go @@ -3,6 +3,7 @@ package openwechat import ( "io" "os" + "sync" "time" ) @@ -29,9 +30,12 @@ type HotReloadStorage io.ReadWriter type jsonFileHotReloadStorage struct { filename string file *os.File + lock sync.Mutex } func (j *jsonFileHotReloadStorage) Read(p []byte) (n int, err error) { + j.lock.Lock() + defer j.lock.Unlock() if j.file == nil { j.file, err = os.OpenFile(j.filename, os.O_RDWR, 0600) if os.IsNotExist(err) { @@ -45,21 +49,22 @@ func (j *jsonFileHotReloadStorage) Read(p []byte) (n int, err error) { } func (j *jsonFileHotReloadStorage) Write(p []byte) (n int, err error) { + j.lock.Lock() + defer j.lock.Unlock() if j.file == nil { j.file, err = os.Create(j.filename) if err != nil { return 0, err } } - // 为什么这里要对文件进行Truncate操作呢? - // 这是为了方便每次Dump的时候对文件进行重新写入, 而不是追加 - // json序列化写入只会调用一次Write方法, 所以不要把这个方法当成io.Writer的Write方法 + // reset offset and truncate file if _, err = j.file.Seek(0, io.SeekStart); err != nil { return } if err = j.file.Truncate(0); err != nil { return } + // json decode only write once return j.file.Write(p) }