github.com/etecs-ru/gnomock@v0.13.2/container.go (about) 1 package gnomock 2 3 import ( 4 "fmt" 5 "os" 6 "strings" 7 ) 8 9 // Container represents a docker container created for testing. Host and Ports 10 // fields should be used to configure the connection to this container. ID 11 // matches the original docker container ID 12 type Container struct { 13 // A unique identifier of this container. The format of this ID may change 14 // in the future. 15 ID string `json:"id,omitempty"` 16 17 // Host name of bound ports 18 // 19 // Default: localhost 20 Host string `json:"host,omitempty"` 21 22 // A collections of ports exposed by this container. Each port has an alias 23 // and an actual port number as exposed on the host 24 Ports NamedPorts `json:"ports,omitempty"` 25 26 gateway string 27 onStop func() error 28 } 29 30 // Address is a convenience function that returns host:port that can be used to 31 // connect to this container. If a container was created with DefaultTCP call, 32 // use DefaultPort as the name. Otherwise, use the name of one of the ports 33 // used during setup 34 func (c *Container) Address(name string) string { 35 p := c.Port(name) 36 if p == 0 { 37 return "" 38 } 39 40 return fmt.Sprintf("%s:%d", c.Host, p) 41 } 42 43 // DefaultAddress return Address() with DefaultPort 44 func (c *Container) DefaultAddress() string { 45 return c.Address(DefaultPort) 46 } 47 48 // Port is a convenience function that returns port number with the provided 49 // name 50 func (c *Container) Port(name string) int { 51 return c.Ports.Get(name).Port 52 } 53 54 // DefaultPort returns Port() with DefaultPort 55 func (c *Container) DefaultPort() int { 56 return c.Port(DefaultPort) 57 } 58 59 // DockerID returns the ID of this container as known to Docker. 60 func (c *Container) DockerID() string { 61 id, _ := parseID(c.ID) 62 return id 63 } 64 65 func isInDocker() bool { 66 env := os.Getenv("GNOMOCK_ENV") 67 return env == "gnomockd" 68 } 69 70 func generateID(id, sidecar string) string { 71 if len(id) > 10 { 72 id = id[:10] 73 } 74 75 if len(sidecar) > 10 { 76 sidecar = sidecar[:10] 77 } 78 79 return fmt.Sprintf("%s-%s", id, sidecar) 80 } 81 82 func parseID(input string) (id, sidecar string) { 83 parts := strings.Split(input, "-") 84 if len(parts) != 2 { 85 return input, "" 86 } 87 88 return parts[0], parts[1] 89 }