github.com/micro/go-micro/examples@v0.0.0-20210105173217-bf4ab679e18b/booking/srv/auth/main.go (about)

     1  package main
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"log"
     7  
     8  	"github.com/micro/go-micro/examples/booking/data"
     9  	"github.com/micro/go-micro/examples/booking/srv/auth/proto"
    10  
    11  	"context"
    12  	"golang.org/x/net/trace"
    13  
    14  	"github.com/micro/go-micro/v2"
    15  	"github.com/micro/go-micro/v2/metadata"
    16  )
    17  
    18  type Auth struct {
    19  	customers map[string]*auth.Customer
    20  }
    21  
    22  // VerifyToken returns a customer from authentication token.
    23  func (s *Auth) VerifyToken(ctx context.Context, req *auth.Request, rsp *auth.Result) error {
    24  	md, _ := metadata.FromContext(ctx)
    25  	traceID := md["traceID"]
    26  
    27  	if tr, ok := trace.FromContext(ctx); ok {
    28  		tr.LazyPrintf("traceID %s", traceID)
    29  	}
    30  
    31  	customer := s.customers[req.AuthToken]
    32  	if customer == nil {
    33  		return errors.New("Invalid Token")
    34  	}
    35  
    36  	rsp.Customer = customer
    37  	return nil
    38  }
    39  
    40  // loadCustomers loads customers from a JSON file.
    41  func loadCustomerData(path string) map[string]*auth.Customer {
    42  	file := data.MustAsset(path)
    43  	customers := []*auth.Customer{}
    44  
    45  	// unmarshal JSON
    46  	if err := json.Unmarshal(file, &customers); err != nil {
    47  		log.Fatalf("Failed to unmarshal json: %v", err)
    48  	}
    49  
    50  	// create customer lookup map
    51  	cache := make(map[string]*auth.Customer)
    52  	for _, c := range customers {
    53  		cache[c.AuthToken] = c
    54  	}
    55  	return cache
    56  }
    57  
    58  func main() {
    59  	service := micro.NewService(
    60  		micro.Name("go.micro.srv.auth"),
    61  	)
    62  
    63  	service.Init()
    64  
    65  	auth.RegisterAuthHandler(service.Server(), &Auth{
    66  		customers: loadCustomerData("data/customers.json"),
    67  	})
    68  
    69  	service.Run()
    70  }