Im real bad at this whole goroutine mutex shit but getting better!

This commit is contained in:
Atridad Lahiji 2024-05-08 15:05:12 -06:00
parent 8fed511607
commit bc3a365dea
No known key found for this signature in database
5 changed files with 23 additions and 38 deletions

View file

@ -2,7 +2,6 @@ package lib
import ( import (
"crypto/tls" "crypto/tls"
"log"
"net/smtp" "net/smtp"
"os" "os"
) )

View file

@ -92,29 +92,19 @@ func SetSSEHeaders(c echo.Context) {
func HandleIncomingMessages(c echo.Context, pubsub pubsub.PubSubMessage, client chan string) { func HandleIncomingMessages(c echo.Context, pubsub pubsub.PubSubMessage, client chan string) {
if c.Response().Writer == nil { if c.Response().Writer == nil {
LogError.Printf("Cannot handle incoming messages: ResponseWriter is nil") LogError.Printf("Cannot handle incoming messages: ResponseWriter is nil")
return return
} }
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
<-c.Request().Context().Done()
cancel()
}()
var mutex sync.Mutex var mutex sync.Mutex
for { for {
select { msg, err := pubsub.ReceiveMessage(c.Request().Context())
case <-ctx.Done():
return
default:
msg, err := pubsub.ReceiveMessage(ctx)
if err != nil { if err != nil {
if err == context.Canceled {
// The client has disconnected. Stop trying to send messages.
return
}
LogError.Printf("Failed to receive message: %v", err) LogError.Printf("Failed to receive message: %v", err)
return return
} }
@ -122,7 +112,7 @@ func HandleIncomingMessages(c echo.Context, pubsub pubsub.PubSubMessage, client
mutex.Lock() mutex.Lock()
if c.Response().Writer != nil { if c.Response().Writer != nil {
_, err = c.Response().Write([]byte(data)) _, err := c.Response().Write([]byte(data))
if err != nil { if err != nil {
LogError.Printf("Failed to write message: %v", err) LogError.Printf("Failed to write message: %v", err)
mutex.Unlock() mutex.Unlock()
@ -140,5 +130,4 @@ func HandleIncomingMessages(c echo.Context, pubsub pubsub.PubSubMessage, client
} }
mutex.Unlock() mutex.Unlock()
} }
}
} }

View file

@ -1,7 +1,6 @@
package lib package lib
import ( import (
"log"
"net/http" "net/http"
"os" "os"

View file

@ -2,7 +2,6 @@ package lib
import ( import (
"html/template" "html/template"
"log"
"net/http" "net/http"
"path/filepath" "path/filepath"
"runtime" "runtime"

View file

@ -5,7 +5,6 @@ import (
"embed" "embed"
"flag" "flag"
"fmt" "fmt"
"log"
"net/http" "net/http"
"time" "time"