server.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. *
  3. * Copyright 2014 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package main
  19. import (
  20. "flag"
  21. "net"
  22. "strconv"
  23. "google.golang.org/grpc"
  24. "google.golang.org/grpc/credentials"
  25. "google.golang.org/grpc/credentials/alts"
  26. "google.golang.org/grpc/grpclog"
  27. "google.golang.org/grpc/interop"
  28. testpb "google.golang.org/grpc/interop/grpc_testing"
  29. "google.golang.org/grpc/testdata"
  30. )
  31. var (
  32. useTLS = flag.Bool("use_tls", false, "Connection uses TLS if true, else plain TCP")
  33. useALTS = flag.Bool("use_alts", false, "Connection uses ALTS if true (this option can only be used on GCP)")
  34. altsHSAddr = flag.String("alts_handshaker_service_address", "", "ALTS handshaker gRPC service address")
  35. certFile = flag.String("tls_cert_file", "", "The TLS cert file")
  36. keyFile = flag.String("tls_key_file", "", "The TLS key file")
  37. port = flag.Int("port", 10000, "The server port")
  38. )
  39. func main() {
  40. flag.Parse()
  41. if *useTLS && *useALTS {
  42. grpclog.Fatalf("use_tls and use_alts cannot be both set to true")
  43. }
  44. p := strconv.Itoa(*port)
  45. lis, err := net.Listen("tcp", ":"+p)
  46. if err != nil {
  47. grpclog.Fatalf("failed to listen: %v", err)
  48. }
  49. var opts []grpc.ServerOption
  50. if *useTLS {
  51. if *certFile == "" {
  52. *certFile = testdata.Path("server1.pem")
  53. }
  54. if *keyFile == "" {
  55. *keyFile = testdata.Path("server1.key")
  56. }
  57. creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile)
  58. if err != nil {
  59. grpclog.Fatalf("Failed to generate credentials %v", err)
  60. }
  61. opts = append(opts, grpc.Creds(creds))
  62. } else if *useALTS {
  63. altsOpts := alts.DefaultServerOptions()
  64. if *altsHSAddr != "" {
  65. altsOpts.HandshakerServiceAddress = *altsHSAddr
  66. }
  67. altsTC := alts.NewServerCreds(altsOpts)
  68. opts = append(opts, grpc.Creds(altsTC))
  69. }
  70. server := grpc.NewServer(opts...)
  71. testpb.RegisterTestServiceServer(server, interop.NewTestServer())
  72. server.Serve(lis)
  73. }