go - Getting websocket connection information in JSON-RPC method -


i using json-rpc on websocket. and, in rpc method (say, multiply in example below), need know connection called method. part below says "// need websocket connection information here". how do so?

package main  import (     "code.google.com/p/go.net/websocket"     "net/http"     "net/rpc"     "net/rpc/jsonrpc" )  type args struct {     int     b int }  type arith int  func (t *arith) multiply(args *args, reply *int) error {     *reply = args.a * args.b     // need websocket connection information here     return nil }  func main() {     rpc.register(new(arith))     http.handle("/conn", websocket.handler(serve))     http.listenandserve("localhost:7000", nil) }  func serve(ws *websocket.conn) {     jsonrpc.serveconn(ws) } 

this challenging because violates abstraction rpc provides. here's strategy suggestion:

google uses context object lots of apis: https://blog.golang.org/context. part of interface value method arbitrary data:

value(key interface{}) interface{} 

that give thread-local storage, used purpose in other programming languages.

so how add context object request? 1 way create new, custom servercodec:

type servercodec interface {     readrequestheader(*request) error     readrequestbody(interface{}) error     // writeresponse must safe concurrent use multiple goroutines.     writeresponse(*response, interface{}) error      close() error } 

your implementation can mirror jsonrpc's:

var params [1]interface{} params[0] = x return json.unmarshal(*c.req.params, &params) 

but before returning, can use bit of reflection , field in params name/type context , fill it. like:

ctx := createcontextsomehow() v := reflect.valueof(x) if v.kind() == reflect.ptr {     v = v.elem()     if v.kind() == reflect.struct {         ctxv := v.fieldbyname("context")         ctxv.set(ctx)     } } 

then change request:

type args struct {     int     b int } 

change to:

type args struct {     int     b int     context context.context } 

kinda clumsy think make work.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -