Skip to content

Commit

Permalink
wsjson: Write messages in a single frame always
Browse files Browse the repository at this point in the history
Closes #315
  • Loading branch information
nhooyr committed Oct 13, 2023
1 parent a633a10 commit 3f26c9f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
7 changes: 7 additions & 0 deletions internal/util/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package util

type WriterFunc func(p []byte) (int, error)

Check failure on line 3 in internal/util/util.go

View workflow job for this annotation

GitHub Actions / lint

exported type WriterFunc should have comment or be unexported

Check failure on line 3 in internal/util/util.go

View workflow job for this annotation

GitHub Actions / lint

exported type WriterFunc should have comment or be unexported

func (f WriterFunc) Write(p []byte) (int, error) {
return f(p)
}
17 changes: 9 additions & 8 deletions wsjson/wsjson.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

"nhooyr.io/websocket"
"nhooyr.io/websocket/internal/bpool"
"nhooyr.io/websocket/internal/util"
"nhooyr.io/websocket/internal/errd"
)

Expand Down Expand Up @@ -51,17 +52,17 @@ func Write(ctx context.Context, c *websocket.Conn, v interface{}) error {
func write(ctx context.Context, c *websocket.Conn, v interface{}) (err error) {
defer errd.Wrap(&err, "failed to write JSON message")

w, err := c.Writer(ctx, websocket.MessageText)
if err != nil {
return err
}

// json.Marshal cannot reuse buffers between calls as it has to return
// a copy of the byte slice but Encoder does as it directly writes to w.
err = json.NewEncoder(w).Encode(v)
err = json.NewEncoder(util.WriterFunc(func(p []byte) (int, error) {
err := c.Write(ctx, websocket.MessageText, p)
if err != nil {
return 0, err
}
return len(p), nil
})).Encode(v)
if err != nil {
return fmt.Errorf("failed to marshal JSON: %w", err)
}

return w.Close()
return nil
}

0 comments on commit 3f26c9f

Please sign in to comment.