Skip to content

Commit

Permalink
document context support
Browse files Browse the repository at this point in the history
  • Loading branch information
powerman committed Oct 11, 2016
1 parent 7815806 commit f78561a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
10 changes: 10 additions & 0 deletions jsonrpc2/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,29 @@ package jsonrpc2

import "context"

// WithContext is an interface which should be implemented by RPC method
// parameters type if you need access to request context in RPC method.
//
// Request context will be same as was provided to corresponding
// ServeConnContext/NewServerCodecContext or context.Background otherwise.
type WithContext interface {
Context() context.Context
SetContext(ctx context.Context)
}

// Ctx can be embedded into your struct with RPC method parameters (if
// that method parameters type is a struct) to make it implement
// WithContext interface and thus have access to request context.
type Ctx struct {
ctx context.Context
}

// Context returns ctx given to preceding SetContext call.
func (c *Ctx) Context() context.Context {
return c.ctx
}

// SetContext saves ctx for succeeding Context calls.
func (c *Ctx) SetContext(ctx context.Context) {
c.ctx = ctx
}
14 changes: 11 additions & 3 deletions jsonrpc2/doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,17 @@ To call such a method you'll have to use client.Call() with []interface{}
in args.
Using context to provide transport-level details with parameters
If you want to have access to transport-level details (or any other
request context data) in RPC method then first parameter of that RPC
method should provide WithContext interface. (If first parameter is a
struct then you can just embed Ctx into your struct as shown in example.)
This way you can get access to client IP address or details of client HTTP
request etc. in RPC method.
Decoding errors on client
Because of net/rpc limitations client.Call() can't return JSON-RPC 2.0
Expand All @@ -54,9 +65,6 @@ HTTP client does not support Batch Request.
Because of net/rpc limitations RPC method MUST NOT return standard
error which begins with '{' and ends with '}'.
Because of net/rpc limitations there is no way to provide
transport-level details (like client's IP) to RPC method.
Current implementation does a lot of sanity checks to conform to
protocol spec. Making most of them optional may improve performance.
*/
Expand Down

0 comments on commit f78561a

Please sign in to comment.