-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
84 lines (71 loc) · 1.55 KB
/
main.go
File metadata and controls
84 lines (71 loc) · 1.55 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
package main
import (
"context"
"fmt"
"log"
"net"
"net/http"
"time"
"github.com/KyloRilo/load-balancer/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
const (
Attempts int = iota
Retry
)
var (
Balancer LoadBalancer = *NewLoadBalancer()
grpcPort = 50501
port = 3030
)
type Server struct {
proto.UnimplementedLoadBalancerServer
}
func (s *Server) AddConn(_ context.Context, in *proto.AddConnReq) (*proto.AddConnResp, error) {
log.Printf("Received: %v", in.String())
err := Balancer.AddConnection(in.GetUrl())
if err != nil {
return &proto.AddConnResp{
Code: 500,
}, err
}
return &proto.AddConnResp{
Code: 200,
}, nil
}
func NewServer() proto.LoadBalancerServer {
return &Server{}
}
func serveGRPC() {
log.Print("Serving GRPC...")
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", grpcPort))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
proto.RegisterLoadBalancerServer(s, NewServer())
reflection.Register(s)
log.Printf("server listening at %v", lis.Addr())
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
func serveHTTP() {
log.Print("Serving HTTP")
httpServer := http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: http.HandlerFunc(Balancer.balance),
}
log.Printf("Load Balancer started at :%d\n", port)
if err := httpServer.ListenAndServe(); err != nil {
log.Fatal(err)
}
}
func main() {
log.Printf("Init...")
go serveGRPC()
go serveHTTP()
go Balancer.healthCheck()
time.Sleep(time.Hour)
}