forked from harlow/go-micro-services
-
Notifications
You must be signed in to change notification settings - Fork 0
/
profile.go
77 lines (65 loc) · 1.75 KB
/
profile.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
package services
import (
"encoding/json"
"fmt"
"log"
"net"
"github.com/grpc-ecosystem/grpc-opentracing/go/otgrpc"
"github.com/harlow/go-micro-services/data"
"github.com/harlow/go-micro-services/internal/proto/profile"
opentracing "github.com/opentracing/opentracing-go"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
// NewProfile returns a new server
func NewProfile(tr opentracing.Tracer) *Profile {
return &Profile{
tracer: tr,
profiles: loadProfiles("data/hotels.json"),
}
}
// Profile implements the profile service
type Profile struct {
profiles map[string]*profile.Hotel
tracer opentracing.Tracer
}
// Run starts the server
func (s *Profile) Run(port int) error {
srv := grpc.NewServer(
grpc.UnaryInterceptor(
otgrpc.OpenTracingServerInterceptor(s.tracer),
),
)
profile.RegisterProfileServer(srv, s)
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
return srv.Serve(lis)
}
// GetProfiles returns hotel profiles for requested IDs
func (s *Profile) GetProfiles(ctx context.Context, req *profile.Request) (*profile.Result, error) {
res := new(profile.Result)
for _, id := range req.HotelIds {
res.Hotels = append(res.Hotels, s.getProfile(id))
}
return res, nil
}
func (s *Profile) getProfile(id string) *profile.Hotel {
return s.profiles[id]
}
// loadProfiles loads hotel profiles from a JSON file.
func loadProfiles(path string) map[string]*profile.Hotel {
var (
file = data.MustAsset(path)
hotels []*profile.Hotel
)
if err := json.Unmarshal(file, &hotels); err != nil {
log.Fatalf("Failed to load json: %v", err)
}
profiles := make(map[string]*profile.Hotel)
for _, hotel := range hotels {
profiles[hotel.Id] = hotel
}
return profiles
}