This repository has been archived on 2023-07-05. You can view files and clone it, but cannot push or open issues or pull requests.
clessy/tg/client.go

50 lines
1.3 KiB
Go
Raw Normal View History

2016-02-09 10:01:05 +00:00
package tg
import (
"bufio"
"encoding/json"
"io"
"log"
)
// UpdateHandler is an update handler for webhook updates
2016-02-09 10:01:05 +00:00
type UpdateHandler func(broker *Broker, message APIMessage)
// BrokerCallback is a callback for broker responses to client requests
type BrokerCallback func(broker *Broker, update BrokerUpdate)
// CreateBrokerClient creates a connection to a broker and sends all webhook updates to a given function
// This is the intended way to create clients, please refer to examples for how to make a simple client
2016-02-09 10:01:05 +00:00
func CreateBrokerClient(brokerAddr string, updateFn UpdateHandler) error {
broker, err := ConnectToBroker(brokerAddr)
if err != nil {
return err
}
defer broker.Close()
in := bufio.NewReader(broker.Socket)
for {
bytes, _, err := in.ReadLine()
if err != nil {
break
}
var update BrokerUpdate
2016-02-09 10:01:05 +00:00
err = json.Unmarshal(bytes, &update)
if err != nil {
log.Printf("[tg - CreateBrokerClient] ERROR reading JSON: %s\r\n", err.Error())
2016-02-09 10:39:00 +00:00
log.Printf("%s\n", string(bytes))
continue
2016-02-09 10:01:05 +00:00
}
if update.Callback == nil {
// It's a generic message: dispatch to UpdateHandler
go updateFn(broker, *(update.Message))
} else {
// It's a response to a request: retrieve callback and call it
go broker.SpliceCallback(*(update.Callback))(broker, update)
}
2016-02-09 10:01:05 +00:00
}
return io.EOF
}