fayec/client.go

92 lines
2.0 KiB
Go
Raw Normal View History

2018-09-05 09:05:16 +00:00
package fayec
2018-09-04 22:55:52 +00:00
import (
"github.com/thesyncim/faye/message"
"github.com/thesyncim/faye/transport"
2018-09-05 09:12:19 +00:00
_ "github.com/thesyncim/faye/transport/websocket"
2018-09-04 22:55:52 +00:00
)
type options struct {
inExt []message.Extension
outExt []message.Extension
2018-09-04 23:04:40 +00:00
transport transport.Transport
2018-09-04 22:55:52 +00:00
}
var defaultOpts = options{
transport: transport.GetTransport("websocket"),
}
//https://faye.jcoglan.com/architecture.html
type client interface {
Subscribe(subscription string, onMsg func(message *message.Message)) error
Publish(subscription string, message *message.Message) error
//todo unsubscribe,etc
}
type Option func(*options)
var _ client = (*Client)(nil)
type Client struct {
opts options
}
func NewClient(url string, opts ...Option) (*Client, error) {
var c Client
c.opts = defaultOpts
for _, opt := range opts {
opt(&c.opts)
}
2018-09-04 23:04:40 +00:00
tops := &transport.Options{
Url: url,
InExt: c.opts.inExt,
OutExt: c.opts.outExt,
}
2018-09-05 09:04:10 +00:00
var err error
if err = c.opts.transport.Init(tops); err != nil {
return nil, err
}
2018-09-04 23:04:40 +00:00
2018-09-05 09:04:10 +00:00
if err = c.opts.transport.Handshake(); err != nil {
2018-09-04 23:04:40 +00:00
return nil, err
}
2018-09-05 09:04:10 +00:00
if err = c.opts.transport.Connect(); err != nil {
return nil, err
}
2018-09-04 22:55:52 +00:00
return &c, nil
}
2018-09-05 09:01:36 +00:00
func WithOutExtension(extension message.Extension) Option {
return func(o *options) {
o.outExt = append(o.outExt, extension)
}
}
func WithExtension(inExt message.Extension, outExt message.Extension) Option {
return func(o *options) {
o.inExt = append(o.inExt, inExt)
o.outExt = append(o.outExt, outExt)
2018-09-05 09:01:36 +00:00
}
}
func WithInExtension(extension message.Extension) Option {
return func(o *options) {
o.inExt = append(o.inExt, extension)
2018-09-05 09:01:36 +00:00
}
}
2018-09-05 09:04:10 +00:00
2018-09-05 09:01:36 +00:00
func WithTransport(t transport.Transport) Option {
return func(o *options) {
o.transport = t
}
}
2018-09-04 22:55:52 +00:00
func (c *Client) Subscribe(subscription string, onMsg func(message *message.Message)) error {
2018-09-05 09:01:36 +00:00
return c.opts.transport.Subscribe(subscription, onMsg)
2018-09-04 22:55:52 +00:00
}
func (c *Client) Publish(subscription string, message *message.Message) error {
2018-09-05 09:01:36 +00:00
return c.opts.transport.Publish(subscription, message)
2018-09-04 22:55:52 +00:00
}