good morning!!!!

Skip to content
Snippets Groups Projects
Commit 52ac4c1c authored by a's avatar a
Browse files

jayzon

parent 41293abe
Branches
Tags v0.0.13
No related merge requests found
...@@ -27,7 +27,6 @@ import ( ...@@ -27,7 +27,6 @@ import (
"time" "time"
"git.tuxpa.in/a/zlog/log" "git.tuxpa.in/a/zlog/log"
jsoniter "github.com/json-iterator/go"
) )
var ( var (
...@@ -286,7 +285,7 @@ func (c *Client) call(ctx context.Context, result any, msg *jsonrpcMessage) erro ...@@ -286,7 +285,7 @@ func (c *Client) call(ctx context.Context, result any, msg *jsonrpcMessage) erro
case len(resp.Result) == 0: case len(resp.Result) == 0:
return ErrNoResult return ErrNoResult
default: default:
return jsoniter.Unmarshal(resp.Result, &result) return jzon.Unmarshal(resp.Result, &result)
} }
} }
...@@ -403,7 +402,7 @@ func (c *Client) BatchCallContext(ctx context.Context, b []BatchElem) error { ...@@ -403,7 +402,7 @@ func (c *Client) BatchCallContext(ctx context.Context, b []BatchElem) error {
elem.Error = ErrNoResult elem.Error = ErrNoResult
continue continue
} }
elem.Error = jsoniter.Unmarshal(resp.Result, elem.Result) elem.Error = jzon.Unmarshal(resp.Result, elem.Result)
} }
return err return err
...@@ -428,7 +427,7 @@ func (c *Client) newMessage(method string, paramsIn ...any) (*jsonrpcMessage, er ...@@ -428,7 +427,7 @@ func (c *Client) newMessage(method string, paramsIn ...any) (*jsonrpcMessage, er
msg := &jsonrpcMessage{ID: c.nextID(), Method: method} msg := &jsonrpcMessage{ID: c.nextID(), Method: method}
if paramsIn != nil { // prevent sending "params":null if paramsIn != nil { // prevent sending "params":null
var err error var err error
if msg.Params, err = jsoniter.Marshal(paramsIn); err != nil { if msg.Params, err = jzon.Marshal(paramsIn); err != nil {
return nil, err return nil, err
} }
} }
...@@ -438,7 +437,7 @@ func (c *Client) newMessageP(method string, paramIn any) (*jsonrpcMessage, error ...@@ -438,7 +437,7 @@ func (c *Client) newMessageP(method string, paramIn any) (*jsonrpcMessage, error
msg := &jsonrpcMessage{ID: c.nextID(), Method: method} msg := &jsonrpcMessage{ID: c.nextID(), Method: method}
if paramIn != nil { // prevent sending "params":null if paramIn != nil { // prevent sending "params":null
var err error var err error
if msg.Params, err = jsoniter.Marshal(paramIn); err != nil { if msg.Params, err = jzon.Marshal(paramIn); err != nil {
return nil, err return nil, err
} }
} }
......
...@@ -3,6 +3,7 @@ module gfx.cafe/open/jrpc ...@@ -3,6 +3,7 @@ module gfx.cafe/open/jrpc
go 1.18 go 1.18
require ( require (
gfx.cafe/util/go/bufpool v0.0.0-20220917112702-95618babdf53
git.tuxpa.in/a/zlog v1.32.0 git.tuxpa.in/a/zlog v1.32.0
github.com/davecgh/go-spew v1.1.1 github.com/davecgh/go-spew v1.1.1
github.com/deckarep/golang-set v1.8.0 github.com/deckarep/golang-set v1.8.0
......
...@@ -30,8 +30,6 @@ import ( ...@@ -30,8 +30,6 @@ import (
"strings" "strings"
"sync" "sync"
"time" "time"
jsoniter "github.com/json-iterator/go"
) )
const ( const (
...@@ -180,7 +178,7 @@ func (c *Client) sendBatchHTTP(ctx context.Context, op *requestOp, msgs []*jsonr ...@@ -180,7 +178,7 @@ func (c *Client) sendBatchHTTP(ctx context.Context, op *requestOp, msgs []*jsonr
} }
func (hc *httpConn) doRequest(ctx context.Context, msg any) (io.ReadCloser, error) { func (hc *httpConn) doRequest(ctx context.Context, msg any) (io.ReadCloser, error) {
body, err := jsoniter.Marshal(msg) body, err := jzon.Marshal(msg)
if err != nil { if err != nil {
return nil, err return nil, err
} }
......
...@@ -31,7 +31,19 @@ import ( ...@@ -31,7 +31,19 @@ import (
jsoniter "github.com/json-iterator/go" jsoniter "github.com/json-iterator/go"
) )
var jzon = jsoniter.ConfigCompatibleWithStandardLibrary var jzon = jsoniter.Config{
IndentionStep: 0,
MarshalFloatWith6Digits: false,
EscapeHTML: true,
SortMapKeys: true,
UseNumber: false,
DisallowUnknownFields: false,
TagKey: "",
OnlyTaggedField: false,
ValidateJsonRawMessage: true,
ObjectFieldMustBeSimpleString: false,
CaseSensitive: false,
}.Froze()
const ( const (
vsn = "2.0" vsn = "2.0"
...@@ -206,7 +218,7 @@ func NewFuncCodec(conn deadlineCloser, encode, decode func(v any) error) ServerC ...@@ -206,7 +218,7 @@ func NewFuncCodec(conn deadlineCloser, encode, decode func(v any) error) ServerC
// messages will use it to include the remote address of the connection. // messages will use it to include the remote address of the connection.
func NewCodec(conn Conn) ServerCodec { func NewCodec(conn Conn) ServerCodec {
enc := jzon.NewEncoder(conn) enc := jzon.NewEncoder(conn)
dec := jzon.NewDecoder(conn) dec := json.NewDecoder(conn)
dec.UseNumber() dec.UseNumber()
return NewFuncCodec(conn, enc.Encode, dec.Decode) return NewFuncCodec(conn, enc.Encode, dec.Decode)
} }
...@@ -269,7 +281,7 @@ func (c *jsonCodec) closed() <-chan any { ...@@ -269,7 +281,7 @@ func (c *jsonCodec) closed() <-chan any {
func parseMessage(raw json.RawMessage) ([]*jsonrpcMessage, bool) { func parseMessage(raw json.RawMessage) ([]*jsonrpcMessage, bool) {
if !isBatch(raw) { if !isBatch(raw) {
msgs := []*jsonrpcMessage{{}} msgs := []*jsonrpcMessage{{}}
jsoniter.Unmarshal(raw, &msgs[0]) jzon.Unmarshal(raw, &msgs[0])
return msgs, false return msgs, false
} }
dec := json.NewDecoder(bytes.NewReader(raw)) dec := json.NewDecoder(bytes.NewReader(raw))
......
...@@ -4,8 +4,6 @@ import ( ...@@ -4,8 +4,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"io" "io"
jsoniter "github.com/json-iterator/go"
) )
type HandlerFunc func(w ResponseWriter, r *Request) type HandlerFunc func(w ResponseWriter, r *Request)
...@@ -31,7 +29,7 @@ type Request struct { ...@@ -31,7 +29,7 @@ type Request struct {
func NewRequest(ctx context.Context, id string, method string, params any) *Request { func NewRequest(ctx context.Context, id string, method string, params any) *Request {
r := &Request{ctx: ctx} r := &Request{ctx: ctx}
pms, _ := jsoniter.Marshal(params) pms, _ := jzon.Marshal(params)
r.msg = jsonrpcMessage{ r.msg = jsonrpcMessage{
ID: NewStringIDPtr(id), ID: NewStringIDPtr(id),
Method: method, Method: method,
...@@ -50,16 +48,16 @@ func (r *Request) Params() json.RawMessage { ...@@ -50,16 +48,16 @@ func (r *Request) Params() json.RawMessage {
func (r *Request) ParamSlice() []any { func (r *Request) ParamSlice() []any {
var params []any var params []any
jsoniter.Unmarshal(r.msg.Params, &params) jzon.Unmarshal(r.msg.Params, &params)
return params return params
} }
func (r *Request) ParamArray(a ...any) error { func (r *Request) ParamArray(a ...any) error {
var params []json.RawMessage var params []json.RawMessage
jsoniter.Unmarshal(r.msg.Params, &params) jzon.Unmarshal(r.msg.Params, &params)
for idx, v := range params { for idx, v := range params {
if len(v) > idx { if len(v) > idx {
err := jsoniter.Unmarshal(v, &a[idx]) err := jzon.Unmarshal(v, &a[idx])
if err != nil { if err != nil {
return err return err
} }
...@@ -71,7 +69,7 @@ func (r *Request) ParamArray(a ...any) error { ...@@ -71,7 +69,7 @@ func (r *Request) ParamArray(a ...any) error {
} }
func (r *Request) ParamInto(v any) error { func (r *Request) ParamInto(v any) error {
return jsoniter.Unmarshal(r.msg.Params, &v) return jzon.Unmarshal(r.msg.Params, &v)
} }
func (r *Request) Context() context.Context { func (r *Request) Context() context.Context {
...@@ -115,7 +113,7 @@ func NewReaderResponseWriterIo(r *Request, w io.Writer) ResponseWriter { ...@@ -115,7 +113,7 @@ func NewReaderResponseWriterIo(r *Request, w io.Writer) ResponseWriter {
} }
func (w *ResponseWriterIo) Send(args any, e error) (err error) { func (w *ResponseWriterIo) Send(args any, e error) (err error) {
enc := jsoniter.ConfigCompatibleWithStandardLibrary.NewEncoder(w.w) enc := jzon.NewEncoder(w.w)
if e != nil { if e != nil {
return enc.Encode(errorMessage(e)) return enc.Encode(errorMessage(e))
} }
......
...@@ -116,10 +116,9 @@ func TestServerShortLivedConn(t *testing.T) { ...@@ -116,10 +116,9 @@ func TestServerShortLivedConn(t *testing.T) {
conn.Write([]byte(request)) conn.Write([]byte(request))
conn.(*net.TCPConn).CloseWrite() conn.(*net.TCPConn).CloseWrite()
// Now try to get the response. // Now try to get the response.
buf := make([]byte, 2000) buf, err := io.ReadAll(conn)
n, err := conn.Read(buf) n := len(buf)
conn.Close() conn.Close()
if err != nil { if err != nil {
t.Fatal("read error:", err) t.Fatal("read error:", err)
} }
......
...@@ -24,9 +24,9 @@ import ( ...@@ -24,9 +24,9 @@ import (
"sync" "sync"
"time" "time"
"gfx.cafe/open/jrpc/wsjson"
"git.tuxpa.in/a/zlog/log" "git.tuxpa.in/a/zlog/log"
"nhooyr.io/websocket" "nhooyr.io/websocket"
"nhooyr.io/websocket/wsjson"
) )
const ( const (
......
...@@ -3,8 +3,6 @@ package jrpc ...@@ -3,8 +3,6 @@ package jrpc
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
jsoniter "github.com/json-iterator/go"
) )
// Version represents a JSON-RPC version. // Version represents a JSON-RPC version.
...@@ -23,13 +21,13 @@ var ( ...@@ -23,13 +21,13 @@ var (
// MarshalJSON implements json.Marshaler. // MarshalJSON implements json.Marshaler.
func (version) MarshalJSON() ([]byte, error) { func (version) MarshalJSON() ([]byte, error) {
return jsoniter.Marshal(Version) return jzon.Marshal(Version)
} }
// UnmarshalJSON implements json.Unmarshaler. // UnmarshalJSON implements json.Unmarshaler.
func (version) UnmarshalJSON(data []byte) error { func (version) UnmarshalJSON(data []byte) error {
version := "" version := ""
if err := jsoniter.Unmarshal(data, &version); err != nil { if err := jzon.Unmarshal(data, &version); err != nil {
return fmt.Errorf("failed to Unmarshal: %w", err) return fmt.Errorf("failed to Unmarshal: %w", err)
} }
if version != Version { if version != Version {
...@@ -95,12 +93,12 @@ func (id *ID) RawMessage() json.RawMessage { ...@@ -95,12 +93,12 @@ func (id *ID) RawMessage() json.RawMessage {
return null return null
} }
if id.name != "" { if id.name != "" {
ans, err := jsoniter.Marshal(id.name) ans, err := jzon.Marshal(id.name)
if err == nil { if err == nil {
return ans return ans
} }
} }
ans, err := jsoniter.Marshal(id.number) ans, err := jzon.Marshal(id.number)
if err == nil { if err == nil {
return ans return ans
} }
...@@ -116,18 +114,18 @@ func (id *ID) MarshalJSON() ([]byte, error) { ...@@ -116,18 +114,18 @@ func (id *ID) MarshalJSON() ([]byte, error) {
return null, nil return null, nil
} }
if id.name != "" { if id.name != "" {
return jsoniter.Marshal(id.name) return jzon.Marshal(id.name)
} }
return jsoniter.Marshal(id.number) return jzon.Marshal(id.number)
} }
// UnmarshalJSON implements json.Unmarshaler. // UnmarshalJSON implements json.Unmarshaler.
func (id *ID) UnmarshalJSON(data []byte) error { func (id *ID) UnmarshalJSON(data []byte) error {
*id = ID{} *id = ID{}
if err := jsoniter.Unmarshal(data, &id.number); err == nil { if err := jzon.Unmarshal(data, &id.number); err == nil {
return nil return nil
} }
if err := jsoniter.Unmarshal(data, &id.name); err == nil { if err := jzon.Unmarshal(data, &id.name); err == nil {
return nil return nil
} }
id.null = true id.null = true
......
package wsjson
import (
"context"
"fmt"
"gfx.cafe/util/go/bufpool"
jsoniter "github.com/json-iterator/go"
"nhooyr.io/websocket"
)
var jzon = jsoniter.Config{
IndentionStep: 0,
MarshalFloatWith6Digits: false,
EscapeHTML: true,
SortMapKeys: true,
UseNumber: false,
DisallowUnknownFields: false,
TagKey: "",
OnlyTaggedField: false,
ValidateJsonRawMessage: true,
ObjectFieldMustBeSimpleString: false,
CaseSensitive: false,
}.Froze()
// 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.Get(512)
defer bufpool.Put(b)
_, err = b.ReadFrom(r)
if err != nil {
return err
}
err = jzon.Unmarshal(b.Bytes(), 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
}
// 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 = jzon.NewEncoder(w).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