This repository has been archived by the owner on Oct 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
133 lines (111 loc) · 2.81 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
. "subscribe/backend-protobuf/go"
"github.com/joho/godotenv"
"github.com/julienschmidt/httprouter"
"github.com/nats-io/go-nats"
"github.com/golang/protobuf/proto"
)
type RawClient struct {
UserId string `json:"userid"`
ClientId string `json:"clientid"`
}
type JsonResponse struct {
Code uint32 `json:"code"`
Message string `json:"message"`
}
var listen string
var natsHost string
var nc *nats.Conn
var connections map[RawClient]chan []byte
func main() {
// Load .env
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
listen = os.Getenv("LISTEN")
natsHost = os.Getenv("NATS")
connections = make(map[RawClient]chan []byte)
// Routes
router := httprouter.New()
router.GET("/subscribe", Subscribe)
// NATS
nc, err = nats.Connect(natsHost)
if err != nil {
log.Fatal(err)
}
nc.Subscribe("res", ResponseHandler)
// Start server
log.Printf("starting server on %s", listen)
log.Fatal(http.ListenAndServe(listen, router))
}
func Subscribe(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
ua := r.Header.Get("X-User-Claim")
if ua == "" {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
var client RawClient
err := json.Unmarshal([]byte(ua), &client)
if err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
recv := make(chan []byte)
connections[client] = recv;
// Refresh connection periodically
resClosed := w.(http.CloseNotifier).CloseNotify()
ticker := time.NewTicker(25 * time.Second)
for {
select {
case msg := <- recv:
fmt.Fprintf(w, "data: %s\n\n", msg)
flusher.Flush()
case <- ticker.C:
w.Write([]byte(":\n\n"))
case <- resClosed:
ticker.Stop()
delete(connections, client)
return
}
}
}
func ResponseHandler(msg *nats.Msg) {
response := Response {}
if err := proto.Unmarshal(msg.Data, &response); err != nil { // Fail quietly
log.Println(err)
return
}
client := RawClient {
UserId: response.Client.Key,
ClientId: response.Client.Client,
}
connection, present := connections[client]
if present {
res := JsonResponse {
Code: response.Code,
Message: string(response.Message),
}
json_string, err := json.Marshal(res)
if err != nil {
log.Println(err)
return
}
connection <- []byte(json_string)
}
}