This repository has been archived by the owner on Nov 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
90 lines (77 loc) · 1.74 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
NSQ demo za golang prezentaciju
*/
package main
import (
"flag"
"net/http"
"sync"
"github.com/gorilla/websocket"
"github.com/minus5/svckit/log"
nsq "github.com/minus5/svckit/nsq"
"github.com/minus5/svckit/signal"
)
var (
nsqtopic = "super.mario"
listen string
prezDir string
upgrader = websocket.Upgrader{} // use default options
producer *nsq.Producer
consumer *nsq.Consumer
ws *websocket.Conn
)
func init() {
flag.StringVar(&listen, "listen", "127.0.0.1:8080", "adresa i port na kome slusam")
flag.StringVar(&prezDir, "prezDir", "./prez", "folder s prezentacijom")
}
// main je glavna ulazna tocka u program
func main() {
log.Info("starting")
defer log.Info("stopped")
producer = nsq.MustNewProducer(nsqtopic)
defer producer.Close()
consumer = nsq.MustNewConsumer(nsqtopic, onNSQMsg)
defer consumer.Close()
// Default static web server
http.Handle("/", http.FileServer(http.Dir(prezDir)))
http.HandleFunc("/ws", serveWs)
go http.ListenAndServe(listen, nil)
// Ovdje cekamo izlaz iz aplikacije
var wg sync.WaitGroup
signal.WaitForInterupt()
wg.Wait()
}
func onNSQMsg(msg *nsq.Message) error {
log.S("poruka", string(msg.Body)).Info("NSQ Receive")
if nil == ws {
return nil
}
if err := ws.WriteMessage(websocket.TextMessage, msg.Body); err != nil {
log.Error(err)
return err
}
return nil
}
func serveWs(w http.ResponseWriter, r *http.Request) {
var err error
if ws, err = upgrader.Upgrade(w, r, nil); err != nil {
log.Error(err)
return
}
defer func() {
ws.Close()
ws = nil
}()
// Read and echo messsages
for {
// Read message
_, msg, err := ws.ReadMessage()
if err != nil {
log.Error(err)
break
}
// Send NSQ
log.S("poruka", string(msg)).Info("NSQ Send")
producer.Publish(msg)
}
}