forked from WLun001/scaling-ws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
62 lines (50 loc) · 1.09 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
package main
import (
"flag"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/nats-io/nats.go"
"log"
"time"
)
var addr = flag.String("addr", ":3000", "api service address")
const subject = "com.scaling-ws.updates"
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
flag.Parse()
nc, err := nats.Connect(nats.DefaultURL)
if err != nil {
log.Fatal(err)
}
ec, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
if err != nil {
log.Fatal(err)
}
if err := nc.LastError(); err != nil {
log.Fatal(err)
}
defer ec.Close()
defer nc.Close()
r := gin.Default()
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:8080"},
AllowMethods: []string{"*"},
AllowHeaders: []string{"*"},
}))
r.POST("/ping", func(c *gin.Context) {
// publish to nats
message := map[string]string{"sendTime": time.Now().Format(time.ANSIC)}
if err := ec.Publish(subject, message); err != nil {
log.Fatal(err)
}
c.JSON(200, gin.H{
"message": "pong",
})
})
return r.Run(*addr)
}