1/* 2Copyright 2016 Google Inc. All Rights Reserved. 3 4Licensed under the Apache License, Version 2.0 (the "License"); 5you may not use this file except in compliance with the License. 6You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10Unless required by applicable law or agreed to in writing, software 11distributed under the License is distributed on an "AS IS" BASIS, 12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13See the License for the specific language governing permissions and 14limitations under the License. 15*/ 16 17package testutil 18 19import ( 20 "net" 21 22 grpc "google.golang.org/grpc" 23) 24 25// A Server is an in-process gRPC server, listening on a system-chosen port on 26// the local loopback interface. Servers are for testing only and are not 27// intended to be used in production code. 28// 29// To create a server, make a new Server, register your handlers, then call 30// Start: 31// 32// srv, err := NewServer() 33// ... 34// mypb.RegisterMyServiceServer(srv.Gsrv, &myHandler) 35// .... 36// srv.Start() 37// 38// Clients should connect to the server with no security: 39// 40// conn, err := grpc.Dial(srv.Addr, grpc.WithInsecure()) 41// ... 42type Server struct { 43 Addr string 44 l net.Listener 45 Gsrv *grpc.Server 46} 47 48// NewServer creates a new Server. The Server will be listening for gRPC connections 49// at the address named by the Addr field, without TLS. 50func NewServer() (*Server, error) { 51 l, err := net.Listen("tcp", "127.0.0.1:0") 52 if err != nil { 53 return nil, err 54 } 55 s := &Server{ 56 Addr: l.Addr().String(), 57 l: l, 58 Gsrv: grpc.NewServer(), 59 } 60 return s, nil 61} 62 63// Start causes the server to start accepting incoming connections. 64// Call Start after registering handlers. 65func (s *Server) Start() { 66 go s.Gsrv.Serve(s.l) 67} 68 69// Close shuts down the server. 70func (s *Server) Close() { 71 s.Gsrv.Stop() 72 s.l.Close() 73} 74