github.com/micro/go-micro/examples@v0.0.0-20210105173217-bf4ab679e18b/booking/srv/profile/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/profile/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 Profile struct {
    18  	hotels map[string]*profile.Hotel
    19  }
    20  
    21  // GetProfiles returns hotel profiles for requested IDs
    22  func (s *Profile) GetProfiles(ctx context.Context, req *profile.Request, rsp *profile.Result) error {
    23  	md, _ := metadata.FromContext(ctx)
    24  	traceID := md["traceID"]
    25  	if tr, ok := trace.FromContext(ctx); ok {
    26  		tr.LazyPrintf("traceID %s", traceID)
    27  	}
    28  
    29  	for _, i := range req.HotelIds {
    30  		rsp.Hotels = append(rsp.Hotels, s.hotels[i])
    31  	}
    32  	return nil
    33  }
    34  
    35  // loadProfiles loads hotel profiles from a JSON file.
    36  func loadProfiles(path string) map[string]*profile.Hotel {
    37  	file := data.MustAsset(path)
    38  
    39  	// unmarshal json profiles
    40  	hotels := []*profile.Hotel{}
    41  	if err := json.Unmarshal(file, &hotels); err != nil {
    42  		log.Fatalf("Failed to load json: %v", err)
    43  	}
    44  
    45  	profiles := make(map[string]*profile.Hotel)
    46  	for _, hotel := range hotels {
    47  		profiles[hotel.Id] = hotel
    48  	}
    49  	return profiles
    50  }
    51  
    52  func main() {
    53  	service := micro.NewService(
    54  		micro.Name("go.micro.srv.profile"),
    55  	)
    56  
    57  	service.Init()
    58  
    59  	profile.RegisterProfileHandler(service.Server(), &Profile{
    60  		hotels: loadProfiles("data/profiles.json"),
    61  	})
    62  
    63  	service.Run()
    64  }