From ba3d85f48b5aa6694cb7aad39fd81299266b592c Mon Sep 17 00:00:00 2001 From: William Petit Date: Thu, 20 Sep 2018 17:20:52 +0200 Subject: [PATCH] Create generic method to implements the request/response pattern --- go.mod | 1 + go.sum | 2 ++ reach/client.go | 29 +++++++++++++++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/go.mod b/go.mod index 08eb7a8..066ee89 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,7 @@ require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/go-chi/chi v3.3.3+incompatible github.com/gorilla/websocket v1.4.0 // indirect + github.com/mitchellh/mapstructure v1.0.0 github.com/pkg/errors v0.8.0 github.com/pmezard/go-difflib v1.0.0 // indirect github.com/stretchr/testify v1.2.2 // indirect diff --git a/go.sum b/go.sum index 4749ce9..eb81ba4 100644 --- a/go.sum +++ b/go.sum @@ -8,6 +8,8 @@ github.com/go-chi/chi v3.3.3+incompatible h1:KHkmBEMNkwKuK4FdQL7N2wOeB9jnIx7jR5w github.com/go-chi/chi v3.3.3+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ= github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/mitchellh/mapstructure v1.0.0 h1:vVpGvMXJPqSDh2VYHF7gsfQj8Ncx+Xw5Y1KHeTRY+7I= +github.com/mitchellh/mapstructure v1.0.0/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= diff --git a/reach/client.go b/reach/client.go index eef832f..742db25 100644 --- a/reach/client.go +++ b/reach/client.go @@ -5,6 +5,7 @@ import ( "forge.cadoles.com/Pyxis/golang-socketio" "forge.cadoles.com/Pyxis/golang-socketio/transport" + "github.com/mitchellh/mapstructure" "github.com/pkg/errors" ) @@ -72,6 +73,34 @@ func (c *client) Close() { c.conn = nil } +func (c *client) fetch(requestEvent string, requestData interface{}, responseEvent string, res interface{}) error { + + var err error + var wg sync.WaitGroup + + wg.Add(1) + + err = c.conn.On(responseEvent, func(_ *gosocketio.Channel, data interface{}) { + err = mapstructure.Decode(data, res) + c.conn.Off(responseEvent) + wg.Done() + }) + if err != nil { + return errors.Wrapf(err, "error while binding to '%s' event", responseEvent) + } + + c.logf("sending '%s' event", requestEvent) + if err = c.conn.Emit(requestEvent, requestData); err != nil { + return errors.Wrapf(err, "error while emitting '%s' event", requestEvent) + } + c.logf("'%s' event sent", requestEvent) + + wg.Wait() + + return err + +} + func (c *client) logf(format string, args ...interface{}) { if c.opts.Logger == nil { return