95 lines
2.4 KiB
Go
95 lines
2.4 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"net"
|
|
"time"
|
|
|
|
pb_get_currenttime "serve_hours/stubs/serve_currenttime"
|
|
pb_serve_hours "serve_hours/stubs/serve_hours"
|
|
|
|
"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_hours.UnimplementedServeHoursServer
|
|
}
|
|
|
|
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) GetHours(ctx context.Context, in *pb_serve_hours.GetHoursRequest) (*pb_serve_hours.GetHoursResponse, error) {
|
|
timezone := in.GetTimezone()
|
|
current_time := GetCurrentTime(timezone)
|
|
return &pb_serve_hours.GetHoursResponse{Hours: current_time.hours}, nil
|
|
}
|
|
|
|
func serve() {
|
|
lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", SERVE_HOURS_HOST, SERVE_HOURS_PORT))
|
|
if err != nil {
|
|
log.Fatalf("failed to listen: %v", err)
|
|
}
|
|
|
|
server := grpc.NewServer()
|
|
pb_serve_hours.RegisterServeHoursServer(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()
|
|
}
|