-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
93 lines (73 loc) · 1.83 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
package main
import (
"CommunicationsModule/base"
"CommunicationsModule/data"
"CommunicationsModule/service"
"fmt"
"github.com/julienschmidt/httprouter"
"google.golang.org/grpc"
"io"
"log"
"net"
"net/http"
"time"
)
func getTextHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprintf(w, base.Message.ReadMessage())
}
func resetTextHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
base.Message.ResetMessage()
fmt.Fprintf(w, base.Message.ReadMessage())
}
func addTextHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
payload := ""
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err == nil {
payload = string(body)
}
base.Message.AddMessage(payload)
fmt.Fprintf(w, base.Message.ReadMessage())
}
func main() {
if base.IsGrpcServer {
go serveGrpc()
serveHttp()
} else {
// Set Up Initial Messages / Wait for Server
for !service.GetExistingMessages() {
time.Sleep(5 * time.Second)
}
// Update Messages
for {
service.SendMessage()
time.Sleep(5 * time.Second)
}
}
}
func serveHttp() {
router := httprouter.New()
router.GET("/", getTextHandler)
//router.PUT("/", addTextHandler)
//router.POST("/", addTextHandler)
router.DELETE("/", resetTextHandler)
fmt.Printf("Starting HTTP Server at port %s \n", base.HttpPort)
l, err := net.Listen("tcp4", base.HttpPort)
if err != nil {
log.Fatal(err)
}
log.Fatal(http.Serve(l, router))
}
func serveGrpc() {
fmt.Printf("Starting gRPC Server at port %s \n", base.GrpcPort)
lis, err := net.Listen("tcp", base.GrpcPort)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := service.Server{}
grpcServer := grpc.NewServer()
data.RegisterMessageServiceServer(grpcServer, &s)
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %s", err)
}
}