github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/internal/codespaces/grpc/test/server.go (about)

     1  package test
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net"
     7  	"strconv"
     8  
     9  	"github.com/ungtb10d/cli/v2/internal/codespaces/grpc/jupyter"
    10  	"google.golang.org/grpc"
    11  )
    12  
    13  const (
    14  	ServerPort = 50051
    15  )
    16  
    17  var (
    18  	JupyterPort      = 1234
    19  	JupyterServerUrl = "http://localhost:1234?token=1234"
    20  	JupyterMessage   = ""
    21  	JupyterResult    = true
    22  )
    23  
    24  type server struct {
    25  	jupyter.UnimplementedJupyterServerHostServer
    26  }
    27  
    28  func (s *server) GetRunningServer(ctx context.Context, in *jupyter.GetRunningServerRequest) (*jupyter.GetRunningServerResponse, error) {
    29  	return &jupyter.GetRunningServerResponse{
    30  		Port:      strconv.Itoa(JupyterPort),
    31  		ServerUrl: JupyterServerUrl,
    32  		Message:   JupyterMessage,
    33  		Result:    JupyterResult,
    34  	}, nil
    35  }
    36  
    37  // Starts the mock gRPC server listening on port 50051
    38  func StartServer(ctx context.Context) error {
    39  	listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", ServerPort))
    40  	if err != nil {
    41  		return fmt.Errorf("failed to listen: %v", err)
    42  	}
    43  	defer listener.Close()
    44  
    45  	s := grpc.NewServer()
    46  	jupyter.RegisterJupyterServerHostServer(s, &server{})
    47  
    48  	ch := make(chan error, 1)
    49  	go func() {
    50  		if err := s.Serve(listener); err != nil {
    51  			ch <- fmt.Errorf("failed to serve: %v", err)
    52  		}
    53  	}()
    54  
    55  	select {
    56  	case <-ctx.Done():
    57  		s.Stop()
    58  		return ctx.Err()
    59  	case err := <-ch:
    60  		return err
    61  	}
    62  }