longpoll

package module
v0.1.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 22, 2025 License: MIT Imports: 12 Imported by: 0

README

go-longpoll

A simple go module for HTTP long polling

Features

  • Full duplex communication alternative to WebSockets
  • Less susceptible to strict firewalls
  • Built in extras eg: Fanout to all peers, topic based subscriptions

Examples

Server Example
// Create a new LongPoll Manager with default settings
manager := longpoll.NewDefaultManager()

// Set callback function
receiveCallback := func(peerUUID string, message longpoll.Message) {
    fmt.Println("Received Message:", string(message.Data))
}
manager.ReceiveCallback = &receiveCallback

// Start the LongPoll Manager
err := manager.Start()
if err != nil {
    log.Fatal(err)
}

// Take input from CLI and send it to "client1"
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Enter messages to send to client1 and press Enter to send")
for {
    // .Scan() waits for a line to be completed, i.e., the user presses Enter.
    scanned := scanner.Scan()
    if !scanned {
        // If we reach EOF or an error occurred, break
        break
    }

    err := manager.Send("client1", scanner.Text(), nil)
    if err != nil {
        log.Println(err)
    }
}

Client Example
// Create a new LongPoll Manager with default settings
manager := longpoll.NewDefaultManager()

// Change port to not clash with the ServerExample
manager.API_Port = 8081

// Set custom UUID
manager.UUID = "client1"

// Set callback function
receiveCallback := func(peerUUID string, message longpoll.Message) {
    fmt.Println("Received Message:", string(message.Data))
}
manager.ReceiveCallback = &receiveCallback

// Start the LongPoll Manager
err := manager.Start()
if err != nil {
    log.Fatal(err)
}

// Add a server peer
err = manager.AddServerPeer("server1", "http://localhost:8080/poll", nil, nil)
if err != nil {
    log.Fatal(err)
}

// Take input from CLI and send it to "server1"
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Enter messages to send to the server and press Enter to send")
for {
    // .Scan() waits for a line to be completed, i.e., the user presses Enter.
    scanned := scanner.Scan()
    if !scanned {
        // If we reach EOF or an error occurred, break
        break
    }

    err := manager.Send("server1", scanner.Text(), nil)
    if err != nil {
        log.Println(err)
    }
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Manager

type Manager struct {
	UUID string

	API_Port           int              // Port to listen on
	API_Path           string           // Path to listen on eg: /poll
	API_Middleware     *gin.HandlerFunc // Middleware to run before each request
	PollLength         time.Duration    // Time before a poll should be refreshed
	PeerExpiry         time.Duration    // Time before a peer is considered expired/offline
	Deadline           time.Duration    // Time before a poll times out
	OutboundBufferSize int              // Size of outbound message buffers

	UpCallback      *func(peerUUID string)              // Function to call when a peer comes online
	DownCallback    *func(peerUUID string)              // Function to call when a peer goes offline
	ReceiveCallback *func(peerUUID string, msg Message) // Function to call when receiving a message
	// contains filtered or unexported fields
}

func NewDefaultManager

func NewDefaultManager() *Manager

NewDefaultManager Creates a new LongPoll Manager with default settings

func (*Manager) AddServerPeer

func (m *Manager) AddServerPeer(uuid string, url string, headers map[string]string, stickyAttributes map[string]string) error

AddServerPeer Adds a server peer to the LongPoll Manager

func (*Manager) AddTopic

func (m *Manager) AddTopic(uuid string, topic string) error

AddTopic Adds a topic to a peer

func (*Manager) DeletePeer

func (m *Manager) DeletePeer(uuid string) error

DeletePeer Deletes a peer from the LongPoll Manager

func (*Manager) FanOut

func (m *Manager) FanOut(data interface{}, attributes map[string]string) error

FanOut Sends a message to all peers

func (*Manager) FanOutSubscribers

func (m *Manager) FanOutSubscribers(data interface{}, attributes map[string]string, topic string) error

FanOutSubscribers Sends a message to all peers subscribed to a given topic

func (*Manager) Forward

func (m *Manager) Forward(peerUUID string, message Message) error

Forward Forwards an existing message to a peer. Locks Mutex!

func (*Manager) GetPeerIP added in v0.1.2

func (m *Manager) GetPeerIP(uuid string) (string, error)

GetPeerIP Gets the IP address of a peer

func (*Manager) GetTopics

func (m *Manager) GetTopics(uuid string) ([]string, error)

GetTopics Gets the topics of a peer

func (*Manager) PeerExists

func (m *Manager) PeerExists(uuid string) bool

PeerExists Checks if a peer exists. This function locks peersMU!

func (*Manager) RemoveTopic

func (m *Manager) RemoveTopic(uuid string, topic string) error

RemoveTopic Removes a topic from a peer

func (*Manager) Send

func (m *Manager) Send(peerUUID string, data interface{}, attributes map[string]string) error

Send Sends a message to a peer. Locks Mutex!

func (*Manager) SetPeerStickyAttributes added in v0.1.1

func (m *Manager) SetPeerStickyAttributes(peerUUID string, attributes map[string]string) error

SetPeerStickyAttributes Sets the sticky attributes of a peer

func (*Manager) SetTopics added in v0.1.3

func (m *Manager) SetTopics(uuid string, topics []string) error

SetTopics Sets the topics of a peer

func (*Manager) Start

func (m *Manager) Start() error

Start Starts the LongPoll Manager API and garbage collection

type Message

type Message struct {
	Data        []byte            `json:"data"`
	Attributes  map[string]string `json:"attributes"`
	MessageID   string            `json:"message_id"`
	PublishTime time.Time         `json:"publish_time"`
}

type Peer added in v0.1.1

type Peer struct {
	UUID string // Unique identifier for this peer

	Ch           chan Message // Buffered channel for outgoing messages to client peers
	LastConsumed time.Time    // Last time this client peer consumed a message

	Topics           []string          // Topics this peer is subscribed to (see FanOutSubscribers())
	StickyAttrbitues map[string]string // Attributes to be appended to every outgoing message

	// Specific to server peers
	IsServer  bool
	ServerURL string            // URL of server running longpoll API
	Headers   map[string]string // Headers to be applied to outgoing requests
	Online    bool
	// contains filtered or unexported fields
}

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL