How to use sango - Golang
I will explain how to use sango from Go language.
To use sango in the Go language, follow the procedure below.
- Get library with go get
- Client implementation
Confirmed environment
- Go 1.3
- Mqtt-golang 4572889 cc 6 f 741 a 6 10 a 3 b b 544 c 90 c 0 3 b f b 763 f
1. Get library with go get
the golang library of Paho Eclipse go get to get in.
go get git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git
2. Client implementation
Connect
The Connect part is common to both Pub / Sub.
package main
import (
"fmt"
"log"
"time"
MQTT "git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git"
)
func main() {
host := "free.mqtt.shiguredo.jp"
port := 1883
user := "example@github"
password := "<password>"
// 接続用の設定を作成します
opts := MQTT.NewClientOptions()
opts.SetUsername(user)
opts.SetPassword(password)
// golangではURIで接続先を指定します。
brokerUri := fmt.Sprintf("tcp://%s:%d", host, port)
opts.AddBroker(brokerUri)
// 設定を元にクライアントを作成します
client := MQTT.NewClient(opts)
// Connectします
_, err := client.Start()
if err != nil {
log.Fatal(err)
}
}
Subscribe
Subscribe is StartSubscription and passes a callback function to a function called.
func onMessageReceived(client *MQTT.MqttClient, message MQTT.Message) {
fmt.Printf("Received message on topic: %s\n", message.Topic())
fmt.Printf("Message: %s\n", message.Payload())
}
func Subscribe(client *MQTT.MqttClient) error {
topic := "example@github/a/b"
qos := 0
// Subscribeするtopicを設定します
topicFilter, err := MQTT.NewTopicFilter(topic, byte(qos))
if err != nil {
return err
}
// Subscribeします
// onMessageReceived はメッセージが届いたら呼び出されるコールバックです
_, err = client.StartSubscription(onMessageReceived, topicFilter)
if err != nil {
return err
}
// そのままではプロセスが終わってしまいますので、待ち受けます
for {
time.Sleep(1 * time.Second)
}
}
Publish
The Publish Publish use. Alternatively, use the MQTT.Message PublishMessage There is also a function called.
func Publish(client *MQTT.MqttClient) error {
topic := "example@github/a/b"
qos := 0
message := "MQTT from golang"
receipt := client.Publish(MQTT.QoS(qos), topic, message)
<-receipt // Publish成功を待ち受ける
return nil
}