github.com/micro/go-micro/examples@v0.0.0-20210105173217-bf4ab679e18b/booking/srv/rate/main.go (about) 1 package main 2 3 import ( 4 "encoding/json" 5 "log" 6 7 "github.com/micro/go-micro/examples/booking/data" 8 "github.com/micro/go-micro/examples/booking/srv/rate/proto" 9 10 "context" 11 "golang.org/x/net/trace" 12 13 "github.com/micro/go-micro/v2" 14 "github.com/micro/go-micro/v2/metadata" 15 ) 16 17 type stay struct { 18 HotelID string 19 InDate string 20 OutDate string 21 } 22 23 type Rate struct { 24 rateTable map[stay]*rate.RatePlan 25 } 26 27 // GetRates gets rates for hotels for specific date range. 28 func (s *Rate) GetRates(ctx context.Context, req *rate.Request, rsp *rate.Result) error { 29 md, _ := metadata.FromContext(ctx) 30 traceID := md["traceID"] 31 32 if tr, ok := trace.FromContext(ctx); ok { 33 tr.LazyPrintf("traceID %s", traceID) 34 } 35 36 for _, hotelID := range req.HotelIds { 37 stay := stay{ 38 HotelID: hotelID, 39 InDate: req.InDate, 40 OutDate: req.OutDate, 41 } 42 if s.rateTable[stay] != nil { 43 rsp.RatePlans = append(rsp.RatePlans, s.rateTable[stay]) 44 } 45 } 46 return nil 47 } 48 49 // loadRates loads rate codes from JSON file. 50 func loadRateTable(path string) map[stay]*rate.RatePlan { 51 file := data.MustAsset("data/rates.json") 52 53 rates := []*rate.RatePlan{} 54 if err := json.Unmarshal(file, &rates); err != nil { 55 log.Fatalf("Failed to load json: %v", err) 56 } 57 58 rateTable := make(map[stay]*rate.RatePlan) 59 for _, ratePlan := range rates { 60 stay := stay{ 61 HotelID: ratePlan.HotelId, 62 InDate: ratePlan.InDate, 63 OutDate: ratePlan.OutDate, 64 } 65 rateTable[stay] = ratePlan 66 } 67 return rateTable 68 } 69 70 func main() { 71 service := micro.NewService( 72 micro.Name("go.micro.srv.rate"), 73 ) 74 75 service.Init() 76 77 rate.RegisterRateHandler(service.Server(), &Rate{ 78 rateTable: loadRateTable("data/rates.json"), 79 }) 80 81 service.Run() 82 }