Add thread-safe write method with mutex synchronization

- Introduce sync.Mutex to protect concurrent writes to response writer
- Add locking mechanism in Write method to prevent race conditions
- Ensure safe and synchronized message writing in multi-threaded contexts
This commit is contained in:
Max 2025-02-24 17:24:34 +08:00
parent 3c51f16d95
commit 101927e343

View file

@ -4,6 +4,7 @@ import (
"fmt"
"os"
"strings"
"sync"
"github.com/fatih/color"
"github.com/gin-gonic/gin"
@ -15,6 +16,8 @@ import (
"github.com/yaoapp/yao/openai"
)
var locker = sync.Mutex{}
// Message the message
type Message struct {
ID string `json:"id,omitempty"` // id for the message
@ -721,6 +724,11 @@ func (m *Message) Callback(fn interface{}) *Message {
// Write writes the message to response writer
func (m *Message) Write(w gin.ResponseWriter) bool {
// Sync write to response writer
locker.Lock()
defer locker.Unlock()
defer func() {
if r := recover(); r != nil {