forked from harlow/go-micro-services
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rate.go
92 lines (77 loc) · 1.93 KB
/
rate.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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/rate"
opentracing "github.com/opentracing/opentracing-go"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
// NewRate returns a new server
func NewRate(tr opentracing.Tracer) *Rate {
return &Rate{
tracer: tr,
rateTable: loadRateTable("data/inventory.json"),
}
}
// Rate implements the rate service
type Rate struct {
rateTable map[stay]*rate.RatePlan
tracer opentracing.Tracer
}
// Run starts the server
func (s *Rate) Run(port int) error {
srv := grpc.NewServer(
grpc.UnaryInterceptor(
otgrpc.OpenTracingServerInterceptor(s.tracer),
),
)
rate.RegisterRateServer(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)
}
// GetRates gets rates for hotels for specific date range.
func (s *Rate) GetRates(ctx context.Context, req *rate.Request) (*rate.Result, error) {
res := new(rate.Result)
for _, hotelID := range req.HotelIds {
stay := stay{
HotelID: hotelID,
InDate: req.InDate,
OutDate: req.OutDate,
}
if s.rateTable[stay] != nil {
res.RatePlans = append(res.RatePlans, s.rateTable[stay])
}
}
return res, nil
}
// loadRates loads rate codes from JSON file.
func loadRateTable(path string) map[stay]*rate.RatePlan {
file := data.MustAsset(path)
rates := []*rate.RatePlan{}
if err := json.Unmarshal(file, &rates); err != nil {
log.Fatalf("Failed to load json: %v", err)
}
rateTable := make(map[stay]*rate.RatePlan)
for _, ratePlan := range rates {
stay := stay{
HotelID: ratePlan.HotelId,
InDate: ratePlan.InDate,
OutDate: ratePlan.OutDate,
}
rateTable[stay] = ratePlan
}
return rateTable
}
type stay struct {
HotelID string
InDate string
OutDate string
}