-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
57 lines (47 loc) · 1.22 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main
import (
"log"
"net/http"
"github.com/julienschmidt/httprouter"
"github.com/sudarshan-reddy/mqtt/mq"
)
const (
apiVersion = "/v1"
)
var lastResponse []byte
func failOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", err, msg)
}
}
func main() {
cfg, err := loadConfigs()
failOnError(err, "failed to load configs")
mqttClient, err := mq.NewClient(cfg.MQTTClient, cfg.MQTTURL, cfg.MQTTTopic, false)
failOnError(err, "failed to load client")
defer mqttClient.Close()
serv := &server{client: mqttClient}
responseCh := make(chan string)
defer close(responseCh)
go serv.startSubscribing(responseCh)
router := httprouter.New()
router.GET(apiVersion+"/currentStatus", currentStatus)
http.ListenAndServe(cfg.ListenAddr, router)
}
type server struct {
client *mq.Client
}
func (s *server) startSubscribing(response chan string) {
for writer := range s.client.Subscribe() {
writer.WritePayload(s)
}
}
func (s *server) Write(p []byte) (n int, err error) {
lastResponse = p
return 0, nil
}
func currentStatus(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
w.Write(lastResponse)
}