good morning!!!!

Skip to content
Snippets Groups Projects
Verified Commit e3dbcc73 authored by a's avatar a
Browse files

remove wsjson

parent 2ed98d94
No related branches found
No related tags found
No related merge requests found
Pipeline #29736 canceled
package wsjson
import (
"bytes"
"encoding/json"
"io"
"log"
"testing"
)
type noTrailingNewlineWriter struct {
w io.Writer
}
func (n *noTrailingNewlineWriter) Write(xs []byte) (int, error) {
if xs[len(xs)-1] == '\n' {
xs = xs[:len(xs)-1]
}
return n.w.Write(xs)
}
func TestNoTrailingNewlineWriter(t *testing.T) {
buf := new(bytes.Buffer)
wr := &noTrailingNewlineWriter{w: buf}
enc := json.NewEncoder(wr)
enc.Encode(map[string]any{"hi": "there", "how": "are", "you": "?"})
enc.Encode(map[string]any{"hi": "there", "how": "are", "you": "?"})
enc.Encode(map[string]any{"hi": "there", "how": "are", "you": "?"})
log.Println(string(buf.Bytes()))
}
package wsjson
import (
"context"
"fmt"
"gfx.cafe/util/go/bufpool"
json "github.com/goccy/go-json"
"gfx.cafe/open/websocket"
)
// Read reads a JSON message from c into v.
// It will reuse buffers in between calls to avoid allocations.
func Read(ctx context.Context, c *websocket.Conn, v interface{}) error {
return read(ctx, c, v)
}
func read(ctx context.Context, c *websocket.Conn, v interface{}) (err error) {
_, r, err := c.Reader(ctx)
if err != nil {
return err
}
b := bufpool.GetStd()
defer bufpool.PutStd(b)
_, err = b.ReadFrom(r)
if err != nil {
return err
}
err = json.NewDecoder(b).Decode(v)
if err != nil {
return fmt.Errorf("failed to unmarshal JSON: %w", err)
}
return nil
}
// Write writes the JSON message v to c.
// It will reuse buffers in between calls to avoid allocations.
func Write(ctx context.Context, c *websocket.Conn, v interface{}) error {
return write(ctx, c, v)
}
func write(ctx context.Context, c *websocket.Conn, v interface{}) (err error) {
w, err := c.Writer(ctx, websocket.MessageText)
if err != nil {
return err
}
st := json.NewEncoder(w)
err = st.Encode(v)
if err != nil {
return fmt.Errorf("failed to marshal JSON: %w", err)
}
return w.Close()
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment