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 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
| var ( argAddress string argCrtFile string argKeyFile string argCAFile string )
var verbose bool var rootCmd *cobra.Command
func init() { rootCmd = &cobra.Command{ Use: "grpc", Short: "demo service", Long: "Top level command for demo service, it provides GRPC service", Run: run, }
rootCmd.Flags().StringVarP(&argAddress, "address", "a", ":3264", "address to listen on") rootCmd.Flags().StringVar(&argCrtFile, "cert-file", "", "certificate file for gRPC TLS authentication") rootCmd.Flags().StringVar(&argKeyFile, "key-file", "", "key file for gRPC TLS authentication") rootCmd.Flags().StringVar(&argCAFile, "ca-file", "", "ca file for gRPC client") rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "verbose output") }
type Service struct { }
func (s *Service) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloReply, error) { md, ok := metadata.FromIncomingContext(ctx) if !ok { return nil, grpc.Errorf(codes.Unauthenticated, "no metadata") }
token := md.Get("token") if len(token) == 0 { return nil, grpc.Errorf(codes.Unauthenticated, "no token") }
fmt.Println("requst:", token[0], req.Name) return &pb.HelloReply{ Message: "hello, " + req.Name, }, nil }
func main() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } }
func run(cmd *cobra.Command, _ []string) { listener, err := net.Listen("tcp", argAddress) if err != nil { panic(err) }
var opts []grpc.ServerOption if argCrtFile != "" && argKeyFile != "" { fmt.Println("enable credentials in the grpc")
if argCAFile == "" { creds, err := credentials.NewServerTLSFromFile(argCrtFile, argKeyFile) if err != nil { panic(err) }
opts = append(opts, grpc.Creds(creds)) } else { cert, err := tls.LoadX509KeyPair(argCrtFile, argKeyFile) if err != nil { panic(err) }
cPool := x509.NewCertPool() clientCert, err := ioutil.ReadFile(argCAFile) if err != nil { panic(err) } if cPool.AppendCertsFromPEM(clientCert) != true { panic(err) }
tlsConfig := tls.Config{ Certificates: []tls.Certificate{cert}, ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: cPool, } opts = append(opts, grpc.Creds(credentials.NewTLS(&tlsConfig)), ) } }
server := grpc.NewServer(opts...) pb.RegisterGreeterServer(server, &Service{})
logrus.WithField("addr", argAddress).Println("Starting server") server.Serve(listener) }
|