github.com/angryronald/go-kit@v0.0.0-20240505173814-ff2bd9c79dbf/test/docker/mockserver/mockserver.go (about)

     1  package mockserver
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"os/exec"
     7  	"sync"
     8  	"time"
     9  
    10  	"github.com/sirupsen/logrus"
    11  )
    12  
    13  var mu sync.Mutex
    14  var upFlag bool
    15  
    16  func init() {
    17  	upFlag = false
    18  }
    19  
    20  // StartMockServer starting mockserver in docker and returning active port being used by mockserver container
    21  func StartMockServer() int {
    22  	mu.Lock()
    23  	if !upFlag {
    24  		// availablePort := docker.GetAvailablePort(1080)
    25  		// Define the command you want to run
    26  		cmd := exec.Command("docker", "run", "-d", "--rm", "-p", fmt.Sprintf("%d:1080", port), "--name", "mockserver", "mockserver/mockserver")
    27  
    28  		// Set the working directory to the location of your docker-compose.yml file
    29  		cmd.Dir = "."
    30  
    31  		// Capture and print the command's output
    32  		output, err := cmd.CombinedOutput()
    33  		if err != nil {
    34  			StopMockServerWithoutLock()
    35  			logrus.Debug("Error:", err)
    36  			os.Exit(1)
    37  		}
    38  
    39  		logrus.Debug("Command Output:", string(output))
    40  
    41  		time.Sleep(2 * time.Second)
    42  
    43  		cmd = exec.Command("docker", "ps", "-a")
    44  
    45  		// Capture and print the command's output
    46  		output, err = cmd.CombinedOutput()
    47  		if err != nil {
    48  			logrus.Debug("Error:", err)
    49  			os.Exit(1)
    50  		}
    51  
    52  		logrus.Debug("Command Output:", string(output))
    53  
    54  		upFlag = true
    55  
    56  		time.Sleep(3 * time.Second)
    57  	}
    58  	mu.Unlock()
    59  	return port
    60  }
    61  
    62  func StopMockServerWithoutLock() {
    63  	// Define the command you want to run
    64  	cmd := exec.Command("docker", "stop", "mockserver")
    65  
    66  	// Set the working directory to the location of your docker-compose.yml file
    67  	cmd.Dir = "."
    68  
    69  	// Capture and print the command's output
    70  	output, err := cmd.CombinedOutput()
    71  	if err != nil {
    72  		logrus.Debug("Error:", err)
    73  		os.Exit(1)
    74  	}
    75  
    76  	logrus.Debug("Command Output:", string(output))
    77  }
    78  
    79  func StopMockServer() {
    80  	mu.Lock()
    81  	if upFlag {
    82  		StopMockServerWithoutLock()
    83  		upFlag = false
    84  	}
    85  	mu.Unlock()
    86  }