Skip to content

Commit

Permalink
generic codec
Browse files Browse the repository at this point in the history
  • Loading branch information
ghatdev committed Feb 6, 2023
1 parent 296f09a commit 53c8336
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 7 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module golang.org/x/net

go 1.17
go 1.18

require (
golang.org/x/sys v0.4.0
Expand Down
12 changes: 6 additions & 6 deletions websocket/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -298,13 +298,13 @@ func (ws *Conn) Config() *Config { return ws.config }
func (ws *Conn) Request() *http.Request { return ws.request }

// Codec represents a symmetric pair of functions that implement a codec.
type Codec struct {
Marshal func(v interface{}) (data []byte, payloadType byte, err error)
type Codec[T any] struct {
Marshal func(v T) (data []byte, payloadType byte, err error)
Unmarshal func(data []byte, payloadType byte, v interface{}) (err error)
}

// Send sends v marshaled by cd.Marshal as single frame to ws.
func (cd Codec) Send(ws *Conn, v interface{}) (err error) {
func (cd Codec[T]) Send(ws *Conn, v T) (err error) {
data, payloadType, err := cd.Marshal(v)
if err != nil {
return err
Expand All @@ -326,7 +326,7 @@ func (cd Codec) Send(ws *Conn, v interface{}) (err error) {
// limit, ErrFrameTooLarge is returned; in this case frame is not read off wire
// completely. The next call to Receive would read and discard leftover data of
// previous oversized frame before processing next frame.
func (cd Codec) Receive(ws *Conn, v interface{}) (err error) {
func (cd Codec[T]) Receive(ws *Conn, v interface{}) (err error) {
ws.rio.Lock()
defer ws.rio.Unlock()
if ws.frameReader != nil {
Expand Down Expand Up @@ -416,7 +416,7 @@ Trivial usage:
data = []byte{0, 1, 2}
websocket.Message.Send(ws, data)
*/
var Message = Codec{marshal, unmarshal}
var Message = Codec[interface{}]{Marshal: marshal, Unmarshal: unmarshal}

func jsonMarshal(v interface{}) (msg []byte, payloadType byte, err error) {
msg, err = json.Marshal(v)
Expand Down Expand Up @@ -446,4 +446,4 @@ Trivial usage:
// send JSON type T
websocket.JSON.Send(ws, data)
*/
var JSON = Codec{jsonMarshal, jsonUnmarshal}
var JSON = Codec[interface{}]{Marshal: jsonMarshal, Unmarshal: jsonUnmarshal}

0 comments on commit 53c8336

Please sign in to comment.