An experimental pub/sub client and server project.
1package server
2
3import (
4 "net"
5 "sync"
6)
7
8// Peer represents a remote connection to the server such as a publisher or subscriber.
9type Peer struct {
10 conn net.Conn
11 connMu sync.Mutex
12}
13
14// New returns a new peer.
15func NewPeer(conn net.Conn) *Peer {
16 return &Peer{
17 conn: conn,
18 }
19}
20
21// Addr returns the peers connections address.
22func (p *Peer) Addr() net.Addr {
23 return p.conn.RemoteAddr()
24}
25
26// ConnOpp represents a set of actions on a connection that can be used synchrnously.
27type ConnOpp func(conn net.Conn) error
28
29// RunConnOperation will run the provided operation. It ensures that it is the only operation that is being
30// run on the connection to ensure any other operations don't get mixed up.
31func (p *Peer) RunConnOperation(op ConnOpp) error {
32 p.connMu.Lock()
33 defer p.connMu.Unlock()
34
35 return op(p.conn)
36}