yats.git

ref: f371af5f199691912f766ce813b5e8df7e5d756c

server/grpc/metric-grpc-server.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
package crudpb

import (
	"context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"log"
	"net"
	"yats-server/crudpb"
)

type server struct {
	crudpb.UnimplementedCRUDServiceServer
	metrics map[string]*crudpb.Metric
}

func (s *server) CreateMetric(ctx context.Context, req *crudpb.CreateMetricRequest) (*crudpb.CreateMetricResponse, error) {
	metric := req.GetMetric()
	s.metrics[metric.Id] = metric
	return &crudpb.CreateMetricResponse{Metric: metric}, nil
}

func (s *server) ReadMetric(ctx context.Context, req *crudpb.ReadMetricRequest) (*crudpb.ReadMetricResponse, error) {
	metric, exists := s.metrics[req.GetId()]
	if !exists {
		return nil, status.Errorf(codes.NotFound, "metric not found")
	}
	return &crudpb.ReadMetricResponse{Metric: metric}, nil
}

func main() {
	lis, err := net.Listen("tcp", ":50051")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	crudpb.RegisterCRUDServiceServer(s, &server{metrics: make(map[string]*crudpb.Metric)})
	log.Println("Server is running on port 50051")
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}