-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.go
More file actions
175 lines (143 loc) · 3.72 KB
/
server.go
File metadata and controls
175 lines (143 loc) · 3.72 KB
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package main
import (
"bustrack/dbs"
"bustrack/models"
"bustrack/myredis"
"bustrack/routes"
"context"
"fmt"
"log"
"net"
"os"
"os/signal"
"strconv"
"strings"
"time"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
func main() {
poolCreatedStatus := myredis.InitPool()
if poolCreatedStatus == true {
e := echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
//CORS
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"*"},
AllowMethods: []string{echo.GET, echo.HEAD, echo.PUT, echo.PATCH, echo.POST, echo.DELETE},
}))
// Routes
routes.Route(e)
// Server
go StartUdpServer()
go func() {
if err := e.Start(":1323"); err != nil {
e.Logger.Info("shutting down the server")
}
}()
// Wait for interrupt signal to gracefully shutdown the server with
// a ttimeout of 10 seconds.
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := e.Shutdown(ctx); err != nil {
e.Logger.Fatal(err)
}
}
//fmt.Println("initialization pool status:" + poolCreatedStatus)
}
// ------------------udp server code block starts here---------------------//
func handleUDPConnection(conn *net.UDPConn) {
// here is where you want to do stuff like read or write to client
buffer := make([]byte, 1024)
n, addr, err := conn.ReadFromUDP(buffer)
fmt.Println("UDP client : ", addr)
fmt.Println("Received from UDP client : ", string(buffer[:n]))
UpdateTripCoords(string(buffer[:n]))
if err != nil {
log.Fatal(err)
}
// NOTE : Need to specify client address in WriteToUDP() function
// otherwise, you will get this error message
// write udp : write: destination address required if you use Write() function instead of WriteToUDP()
if err != nil {
log.Println(err)
}
}
func StartUdpServer() {
hostName := GetCurretIp()
portNum := "8085"
service := hostName + ":" + portNum
udpAddr, err := net.ResolveUDPAddr("udp4", service)
fmt.Println(udpAddr)
if err != nil {
log.Fatal(err)
}
// setup listener for incoming UDP connection
ln, err := net.ListenUDP("udp", udpAddr)
if err != nil {
log.Fatal(err)
}
fmt.Println("UDP server up and listening on port 8085")
defer ln.Close()
for {
// wait for UDP client to connect
handleUDPConnection(ln)
}
}
func GetCurretIp() string {
addrs, err := net.InterfaceAddrs()
currentIP := "0.0.0.0"
if err != nil {
os.Stderr.WriteString("Oops: " + err.Error() + "\n")
os.Exit(1)
}
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
currentIP = ipnet.IP.String()
}
}
}
return currentIP
}
//------------------------------udp server block ends here-----------------//
//UpdateTripCoords is to add current location to existing trip
func UpdateTripCoords(locationstamp string) {
var coords, topic, tripid string
temp := strings.Split(locationstamp, "|")
topic = temp[0]
coords = temp[1]
if strings.Compare(coords, "end") > 0 {
//to publish to the redis topic
go publishToRedis(topic, coords)
tripid = strings.SplitAfter(topic, "trip")[1]
//to update things in database
go func() {
_, err := models.UpdateTripDetails(dbs.DB, coords, stringtoInt(tripid))
if err != nil {
fmt.Println("Error is", err)
}
}()
} else {
go publishToRedis(topic, coords)
}
}
func stringtoInt(s string) int {
str, _ := strconv.Atoi(s)
return str
}
func publishToRedis(topic, coords string) {
client := myredis.GetConnection()
defer client.Close()
fmt.Println(coords)
_, err := client.Do("PUBLISH", topic, coords)
if err != nil {
fmt.Println("error")
fmt.Println(err)
}
}