1
0
Fork 0
mirror of https://github.com/sourcegraph/jsonrpc2.git synced 2026-06-16 20:20:03 +02:00
jsonrpc2/call_opt.go
Sam Herrmann 8012d49686
Add ability to omit params member from request (#62)
The JSON-RPC 2.0 specification allows the params member of a request to
be omitted [1]. Before this commit, this library did not allow the
params member to be omitted when sending a request. When the params
argument of the Conn.Call/Conn.DispatchCall or Conn.Notify method was
set to nil, then Request.Params was set to the JSON encoding of nil
which is null.

This commit adds a CallOption named OmitNilParams. If OmitNilParams is
used when sending a request with params set to nil, then the params
member in the JSON encoding of Request is omitted. If the OmitNilParams
option is not used then the previous behavior is maintained. In other
words, the changes in this commit are backwards compatible.

References
[1]: https://www.jsonrpc.org/specification#request_object
2023-01-24 08:47:36 +02:00

57 lines
1.6 KiB
Go

package jsonrpc2
// CallOption is an option that can be provided to (*Conn).Call to
// configure custom behavior. See Meta.
type CallOption interface {
apply(r *Request) error
}
type callOptionFunc func(r *Request) error
func (c callOptionFunc) apply(r *Request) error { return c(r) }
// Meta returns a call option which attaches the given meta object to
// the JSON-RPC 2.0 request (this is a Sourcegraph extension to JSON
// RPC 2.0 for carrying metadata).
func Meta(meta interface{}) CallOption {
return callOptionFunc(func(r *Request) error {
return r.SetMeta(meta)
})
}
// ExtraField returns a call option which attaches the given name/value pair to
// the JSON-RPC 2.0 request. This can be used to add arbitrary extensions to
// JSON RPC 2.0.
func ExtraField(name string, value interface{}) CallOption {
return callOptionFunc(func(r *Request) error {
return r.SetExtraField(name, value)
})
}
// PickID returns a call option which sets the ID on a request. Care must be
// taken to ensure there are no conflicts with any previously picked ID, nor
// with the default sequence ID.
func PickID(id ID) CallOption {
return callOptionFunc(func(r *Request) error {
r.ID = id
return nil
})
}
// StringID returns a call option that instructs the request ID to be set as a
// string.
func StringID() CallOption {
return callOptionFunc(func(r *Request) error {
r.ID.IsString = true
return nil
})
}
// OmitNilParams returns a call option that instructs requests to omit params
// values of nil instead of JSON encoding them to null.
func OmitNilParams() CallOption {
return callOptionFunc(func(r *Request) error {
r.OmitNilParams = true
return nil
})
}