Serve seconds

This commit is contained in:
Eden Kirin
2023-03-20 23:25:53 +01:00
parent 1876158d9d
commit 3776bdca24
21 changed files with 1373 additions and 44 deletions

94
src/serve_minutes/main.go Normal file
View File

@ -0,0 +1,94 @@
package main
import (
"context"
"fmt"
"log"
"net"
"time"
pb_get_currenttime "serve_minutes/stubs/serve_currenttime"
pb_serve_minutes "serve_minutes/stubs/serve_minutes"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
const SERVE_CURRENTTIME_HOST = "localhost"
const SERVE_CURRENTTIME_PORT = 50000
const SERVE_HOURS_HOST = "localhost"
const SERVE_HOURS_PORT = 50001
const SERVE_MINUTES_HOST = "localhost"
const SERVE_MINUTES_PORT = 50002
const SERVE_SECONDS_HOST = "localhost"
const SERVE_SECONDS_PORT = 50003
const SERVE_MILLISECONDS_HOST = "localhost"
const SERVE_MILLISECONDS_PORT = 50004
type grpc_server struct {
pb_serve_minutes.UnimplementedServeMinutesServer
}
type currentTimeResponse struct {
hours uint32
minutes uint32
seconds uint32
milliseconds uint32
formatted_time string
}
func GetCurrentTime(timezone string) currentTimeResponse {
conn, err := grpc.Dial(
fmt.Sprintf("%s:%d", SERVE_CURRENTTIME_HOST, SERVE_CURRENTTIME_PORT),
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb_get_currenttime.NewServeCurrentTimeServiceClient(conn)
// Contact the server and print out its response.
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
r, err := c.GetCurrentTime(
ctx,
&pb_get_currenttime.GetCurrentTimeRequest{Timezone: timezone},
)
if err != nil {
log.Fatalf("could not greet: %v", err)
}
result := currentTimeResponse{
hours: r.Hours,
minutes: r.Minutes,
seconds: r.Seconds,
milliseconds: r.Milliseconds,
formatted_time: r.FormattedTime,
}
return result
}
func (s *grpc_server) GetMinutes(ctx context.Context, in *pb_serve_minutes.GetMinutesRequest) (*pb_serve_minutes.GetMinutesResponse, error) {
timezone := in.GetTimezone()
current_time := GetCurrentTime(timezone)
return &pb_serve_minutes.GetMinutesResponse{Minutes: current_time.minutes}, nil
}
func serve() {
lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", SERVE_MINUTES_HOST, SERVE_MINUTES_PORT))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
server := grpc.NewServer()
pb_serve_minutes.RegisterServeMinutesServer(server, &grpc_server{})
log.Printf("server listening at %v", lis.Addr())
if err := server.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
func main() {
serve()
}