repos / pico

pico services - prose.sh, pastes.sh, imgs.sh, feeds.sh, pgs.sh
git clone https://github.com/picosh/pico.git

commit
aa5b8d3
parent
5751e64
author
Antonio Mika
date
2024-10-03 21:48:50 +0000 UTC
Use once to close channels
1 files changed,  +32, -25
M shared/sendlog.go
+32, -25
 1@@ -17,16 +17,17 @@ import (
 2 )
 3 
 4 type SendLogWriter struct {
 5-	SSHClient  *ssh.Client
 6-	Session    *ssh.Session
 7-	StdinPipe  io.WriteCloser
 8-	Done       chan struct{}
 9-	Messages   chan []byte
10-	Timeout    time.Duration
11-	BufferSize int
12-	closeOnce  sync.Once
13-	startOnce  sync.Once
14-	connecMu   sync.Mutex
15+	SSHClient        *ssh.Client
16+	Session          *ssh.Session
17+	StdinPipe        io.WriteCloser
18+	Done             chan struct{}
19+	Messages         chan []byte
20+	Timeout          time.Duration
21+	BufferSize       int
22+	closeOnce        sync.Once
23+	closeMessageOnce sync.Once
24+	startOnce        sync.Once
25+	connecMu         sync.Mutex
26 }
27 
28 func (c *SendLogWriter) Close() error {
29@@ -34,11 +35,15 @@ func (c *SendLogWriter) Close() error {
30 	defer c.connecMu.Unlock()
31 
32 	if c.Done != nil {
33-		close(c.Done)
34+		c.closeOnce.Do(func() {
35+			close(c.Done)
36+		})
37 	}
38 
39 	if c.Messages != nil {
40-		close(c.Messages)
41+		c.closeMessageOnce.Do(func() {
42+			close(c.Messages)
43+		})
44 	}
45 
46 	var errs []error
47@@ -111,22 +116,24 @@ func (c *SendLogWriter) Open() error {
48 }
49 
50 func (c *SendLogWriter) Start() {
51-	go func() {
52-		defer c.Reconnect()
53-
54-		for {
55-			select {
56-			case data, ok := <-c.Messages:
57-				_, err := c.StdinPipe.Write(data)
58-				if !ok || err != nil {
59-					slog.Error("received error on write, reopening logger", "error", err)
60+	c.startOnce.Do(func() {
61+		go func() {
62+			defer c.Reconnect()
63+
64+			for {
65+				select {
66+				case data, ok := <-c.Messages:
67+					_, err := c.StdinPipe.Write(data)
68+					if !ok || err != nil {
69+						slog.Error("received error on write, reopening logger", "error", err)
70+						return
71+					}
72+				case <-c.Done:
73 					return
74 				}
75-			case <-c.Done:
76-				return
77 			}
78-		}
79-	}()
80+		}()
81+	})
82 }
83 
84 func (c *SendLogWriter) Write(data []byte) (int, error) {