Skip to content

Commit

Permalink
Merge pull request #3 from amirhnajafiz/2-client-null-handler
Browse files Browse the repository at this point in the history
2 client null handler
  • Loading branch information
amirhnajafiz authored Aug 11, 2022
2 parents 9e3a27d + cdf4828 commit 4d1899a
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions internal/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ import (
"time"
)

// we need safety timeout, to prevent send more than
// one message in http request.
const (
safetyTimeout = 1
)

// client is our user application handler.
type client struct {
// map of topics
Expand Down Expand Up @@ -79,7 +85,9 @@ func (c *client) listen() {

// handle will execute the topic handler method.
func (c *client) handle(m message) {
c.topics[m.Topic](m.Data)
if handler, ok := c.topics[m.Topic]; ok {
handler(m.Data)
}
}

// close will terminate everything.
Expand All @@ -94,27 +102,29 @@ func (c *client) Publish(topic string, data []byte) error {
return err
}

time.Sleep(1 * time.Millisecond)
time.Sleep(safetyTimeout * time.Millisecond)

return nil
}

// Subscribe subscribes over broker.
func (c *client) Subscribe(topic string, handler MessageHandler) {
// set a handler for given topic
c.topics[topic] = handler

// send an http request to broker server
err := c.network.send(encodeMessage(newMessage(Subscribe, topic, nil)))
if err != nil {
log.Fatal(err)
}

time.Sleep(1 * time.Millisecond)

// set a handler for given topic
c.topics[topic] = handler
time.Sleep(safetyTimeout * time.Millisecond)
}

// Unsubscribe removes client from subscribing over a topic.
func (c *client) Unsubscribe(topic string) {
_ = c.network.send(encodeMessage(newMessage(Unsubscribe, topic, nil)))
time.Sleep(1 * time.Millisecond)
time.Sleep(safetyTimeout * time.Millisecond)

// remove topic and its handler
delete(c.topics, topic)
Expand Down

0 comments on commit 4d1899a

Please sign in to comment.