container

package module
v0.1.0-alpha002 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 18, 2025 License: Apache-2.0 Imports: 34 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const (
	// StdoutLog is the log type for STDOUT
	StdoutLog = "STDOUT"

	// StderrLog is the log type for STDERR
	StderrLog = "STDERR"
)

Variables

View Source
var DefaultLoggingHook = func(logger *slog.Logger) LifecycleHooks {
	return LifecycleHooks{
		PreCreates: []DefinitionHook{
			func(_ context.Context, def *Definition) error {
				logger.Info("Creating container", "image", def.image)
				return nil
			},
		},
		PostCreates: []ContainerHook{
			func(_ context.Context, c *Container) error {
				logger.Info("Container created", "containerID", c.shortID)
				return nil
			},
		},
		PreStarts: []ContainerHook{
			func(_ context.Context, c *Container) error {
				logger.Info("Starting container", "containerID", c.shortID)
				return nil
			},
		},
		PostStarts: []ContainerHook{
			func(_ context.Context, c *Container) error {
				logger.Info("Container started", "containerID", c.shortID)
				return nil
			},
		},
		PostReadies: []ContainerHook{
			func(_ context.Context, c *Container) error {
				logger.Info("Container is ready", "containerID", c.shortID)
				return nil
			},
		},
		PreStops: []ContainerHook{
			func(_ context.Context, c *Container) error {
				logger.Info("Stopping container", "containerID", c.shortID)
				return nil
			},
		},
		PostStops: []ContainerHook{
			func(_ context.Context, c *Container) error {
				logger.Info("Container stopped", "containerID", c.shortID)
				return nil
			},
		},
		PreTerminates: []ContainerHook{
			func(_ context.Context, c *Container) error {
				logger.Info("Terminating container", "containerID", c.shortID)
				return nil
			},
		},
		PostTerminates: []ContainerHook{
			func(_ context.Context, c *Container) error {
				logger.Info("Container terminated", "containerID", c.shortID)
				return nil
			},
		},
	}
}

DefaultLoggingHook is a hook that will log the container lifecycle events

View Source
var ErrReuseEmptyName = errors.New("with reuse option a container name mustn't be empty")

Functions

func Cleanup

func Cleanup(tb testing.TB, ctr TerminableContainer, options ...TerminateOption)

Cleanup is a helper function that schedules a TerminableContainer to be terminated when the test ends.

This should be called directly after (before any error check) [Create](...) in a test to ensure the container is pruned when the function ends. If the container is nil, it's a no-op.

func Terminate

func Terminate(ctr TerminableContainer, options ...TerminateOption) error

Terminate calls [TerminableContainer.Terminate] on the container if it is not nil.

This should be called as a defer directly after [Create](...) to ensure the container is terminated when the function ends.

func Version

func Version() string

Version returns the version of the container package.

Types

type Container

type Container struct {
	// contains filtered or unexported fields
}

Container represents a container

Example (Copy)
package main

import (
	"bytes"
	"context"
	"fmt"
	"io"

	"github.com/docker/go-sdk/container"
)

func main() {
	ctr, err := container.Run(context.Background(), container.WithImage("alpine:latest"))
	fmt.Println(err)

	content := []byte("Hello, World!")

	err = ctr.CopyToContainer(context.Background(), content, "/tmp/test.txt", 0o644)
	fmt.Println(err)

	rc, err := ctr.CopyFromContainer(context.Background(), "/tmp/test.txt")
	fmt.Println(err)

	buf := new(bytes.Buffer)
	_, err = io.Copy(buf, rc)
	fmt.Println(err)
	fmt.Println(buf.String())

	err = ctr.Terminate(context.Background())
	fmt.Println(err)

}
Output:

<nil>
<nil>
<nil>
<nil>
Hello, World!
<nil>
Example (Lifecycle)
package main

import (
	"context"
	"fmt"

	"github.com/docker/go-sdk/container"
)

func main() {
	ctr, err := container.Run(
		context.Background(),
		container.WithImage("alpine:latest"),
		container.WithNoStart(),
	)

	fmt.Println(err)

	err = ctr.Start(context.Background())
	fmt.Println(err)

	err = ctr.Stop(context.Background())
	fmt.Println(err)

	err = ctr.Start(context.Background())
	fmt.Println(err)

	err = ctr.Terminate(context.Background())
	fmt.Println(err)

}
Output:

<nil>
<nil>
<nil>
<nil>
<nil>

func Run

func Run(ctx context.Context, opts ...ContainerCustomizer) (*Container, error)

Run is a convenience function that creates a new container and starts it. By default, the container is started after creation, unless requested otherwise using the WithNoStart option.

Example
package main

import (
	"context"
	"fmt"

	"github.com/docker/go-sdk/container"
)

func main() {
	ctr, err := container.Run(context.Background(), container.WithImage("alpine:latest"))
	fmt.Println(err)
	fmt.Println(ctr.ID() != "")

	err = ctr.Terminate(context.Background())
	fmt.Println(err)

}
Output:

<nil>
true
<nil>

func (*Container) ContainerIP

func (c *Container) ContainerIP(ctx context.Context) (string, error)

ContainerIP gets the IP address of the primary network within the container. If there are multiple networks, it returns an empty string.

func (*Container) ContainerIPs

func (c *Container) ContainerIPs(ctx context.Context) ([]string, error)

ContainerIPs gets the IP addresses of all the networks within the container.

func (*Container) CopyFromContainer

func (c *Container) CopyFromContainer(ctx context.Context, containerFilePath string) (io.ReadCloser, error)

CopyFromContainer copies a file from the container to the local filesystem.

func (*Container) CopyToContainer

func (c *Container) CopyToContainer(ctx context.Context, fileContent []byte, containerFilePath string, fileMode int64) error

CopyToContainer copies fileContent data to a file in container

func (*Container) Exec

func (c *Container) Exec(ctx context.Context, cmd []string, options ...exec.ProcessOption) (int, io.Reader, error)

Exec executes a command in the current container. It returns the exit status of the executed command, an io.Reader containing the combined stdout and stderr, and any encountered error. Note that reading directly from the io.Reader may result in unexpected bytes due to custom stream multiplexing headers. Use [cexec.Multiplexed] option to read the combined output without the multiplexing headers. Alternatively, to separate the stdout and stderr from io.Reader and interpret these headers properly, github.com/docker/docker/pkg/stdcopy.StdCopy from the Docker API should be used.

Example
package main

import (
	"bytes"
	"context"
	"fmt"
	"io"

	"github.com/docker/go-sdk/container"
	"github.com/docker/go-sdk/container/exec"
)

func main() {
	ctr, err := container.Run(context.Background(), container.WithImage("nginx:alpine"))
	fmt.Println(err)

	code, rc, err := ctr.Exec(
		context.Background(),
		[]string{"pwd"},
		exec.Multiplexed(),
		exec.WithWorkingDir("/usr/share/nginx/html"),
	)
	fmt.Println(err)
	fmt.Println(code)

	buf := new(bytes.Buffer)
	_, err = io.Copy(buf, rc)
	fmt.Println(err)
	fmt.Print(buf.String()) // not adding a newline to the output

	err = ctr.Terminate(context.Background())
	fmt.Println(err)

}
Output:

<nil>
<nil>
0
<nil>
/usr/share/nginx/html
<nil>

func (*Container) GetLogProductionErrorChannel

func (c *Container) GetLogProductionErrorChannel() <-chan error

GetLogProductionErrorChannel exposes the only way for the consumer to be able to listen to errors and react to them.

func (*Container) Host

func (c *Container) Host(ctx context.Context) (string, error)

Host gets host (ip or name) of the docker daemon where the container port is exposed Warning: this is based on your Docker host setting. Will fail if using an SSH tunnel

func (*Container) ID

func (c *Container) ID() string

ID returns the container ID

func (*Container) Image

func (c *Container) Image() string

Image returns the image used by the container.

func (*Container) Inspect

Inspect returns the container's raw info

Example
package main

import (
	"context"
	"fmt"

	"github.com/docker/go-sdk/container"
)

func main() {
	ctr, err := container.Run(context.Background(), container.WithImage("alpine:latest"))
	fmt.Println(err)

	inspect, err := ctr.Inspect(context.Background())
	fmt.Println(err)
	fmt.Println(inspect.ID != "")

	err = ctr.Terminate(context.Background())
	fmt.Println(err)

}
Output:

<nil>
<nil>
true
<nil>

func (*Container) Logger

func (c *Container) Logger() *slog.Logger

Logger returns the logger for the container.

func (*Container) Logs

func (c *Container) Logs(ctx context.Context) (io.ReadCloser, error)

Logs will fetch both STDOUT and STDERR from the current container. Returns a ReadCloser and leaves it up to the caller to extract what it wants.

Example
package main

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"strings"

	"github.com/docker/go-sdk/container"
)

func main() {
	ctr, err := container.Run(context.Background(), container.WithImage("hello-world:latest"))
	fmt.Println(err)

	logs, err := ctr.Logs(context.Background())
	fmt.Println(err)

	buf := new(bytes.Buffer)
	_, err = io.Copy(buf, logs)
	fmt.Println(err)
	fmt.Println(strings.Contains(buf.String(), "Hello from Docker!"))

	err = ctr.Terminate(context.Background())
	fmt.Println(err)

}
Output:

<nil>
<nil>
<nil>
true
<nil>

func (*Container) MappedPort

func (c *Container) MappedPort(ctx context.Context, port nat.Port) (nat.Port, error)

MappedPort gets externally mapped port for a container port

func (*Container) NetworkAliases

func (c *Container) NetworkAliases(ctx context.Context) (map[string][]string, error)

NetworkAliases gets the aliases of the container for the networks it is attached to.

func (*Container) Networks

func (c *Container) Networks(ctx context.Context) ([]string, error)

Networks gets the names of the networks the container is attached to.

func (*Container) ShortID

func (c *Container) ShortID() string

ShortID returns the short container ID, using the first 12 characters of the ID

func (*Container) Start

func (c *Container) Start(ctx context.Context) error

Start will start an already created container

func (*Container) State

func (c *Container) State(ctx context.Context) (*container.State, error)

State returns container's running state.

func (*Container) Stop

func (c *Container) Stop(ctx context.Context, opts ...StopOption) error

Stop stops the container.

In case the container fails to stop gracefully within a time frame specified by the timeout argument, it is forcefully terminated (killed).

If no timeout is passed, the default StopTimeout value is used, 10 seconds, otherwise the engine default. A negative timeout value can be specified, meaning no timeout, i.e. no forceful termination is performed.

All hooks are called in the following order:

  • [LifecycleHooks.PreStops]
  • [LifecycleHooks.PostStops]

If the container is already stopped, the method is a no-op.

func (*Container) Terminate

func (c *Container) Terminate(ctx context.Context, opts ...TerminateOption) error

Terminate calls stops and then removes the container including its volumes. If its image was built it and all child images are also removed unless the [FromDockerfile.KeepImage] on the [ContainerRequest] was set to true.

The following hooks are called in order:

  • [LifecycleHooks.PreTerminates]
  • [LifecycleHooks.PostTerminates]

Default: timeout is 10 seconds.

Example
package main

import (
	"context"
	"fmt"

	"github.com/docker/go-sdk/container"
)

func main() {
	ctr, err := container.Run(context.Background(), container.WithImage("alpine:latest"))
	fmt.Println(err)

	err = ctr.Terminate(context.Background())
	fmt.Println(err)

}
Output:

<nil>
<nil>

type ContainerCustomizer

type ContainerCustomizer interface {
	Customize(def *Definition) error
}

ContainerCustomizer is an interface that can be used to configure the container definition. The passed definition is merged with the default one.

type ContainerHook

type ContainerHook func(ctx context.Context, ctr *Container) error

ContainerHook is a hook that is called after a container is created It can be used to modify the state of the container after it is created, using the different lifecycle hooks that are available: - Created - Starting - Started - Readied - Stopping - Stopped - Terminating - Terminated It receives a Container, modify it and return an error if needed.

type CustomHubSubstitutor

type CustomHubSubstitutor struct {
	// contains filtered or unexported fields
}

CustomHubSubstitutor represents a way to substitute the hub of an image with a custom one, using provided value with respect to the HubImageNamePrefix configuration value.

func NewCustomHubSubstitutor

func NewCustomHubSubstitutor(hub string) CustomHubSubstitutor

NewCustomHubSubstitutor creates a new CustomHubSubstitutor

func (CustomHubSubstitutor) Description

func (c CustomHubSubstitutor) Description() string

Description returns the name of the type and a short description of how it modifies the image.

func (CustomHubSubstitutor) Substitute

func (c CustomHubSubstitutor) Substitute(image string) (string, error)

Substitute replaces the hub of the image with the provided one, with certain conditions:

  • if the hub is empty, the image is returned as is.
  • if the image already contains a registry, the image is returned as is.

type CustomizeDefinitionOption

type CustomizeDefinitionOption func(def *Definition) error

CustomizeDefinitionOption is a type that can be used to configure the container definition. The passed definition is merged with the default one.

func WithAdditionalLifecycleHooks

func WithAdditionalLifecycleHooks(hooks ...LifecycleHooks) CustomizeDefinitionOption

WithAdditionalLifecycleHooks appends lifecycle hooks to the existing ones for a container

func WithAdditionalWaitStrategy

func WithAdditionalWaitStrategy(strategies ...wait.Strategy) CustomizeDefinitionOption

WithAdditionalWaitStrategy appends the wait strategy for a container, using 60 seconds as deadline

func WithAdditionalWaitStrategyAndDeadline

func WithAdditionalWaitStrategyAndDeadline(deadline time.Duration, strategies ...wait.Strategy) CustomizeDefinitionOption

WithAdditionalWaitStrategyAndDeadline appends the wait strategy for a container, including deadline

func WithAfterReadyCommand

func WithAfterReadyCommand(execs ...Executable) CustomizeDefinitionOption

WithAfterReadyCommand will execute the command representation of each Executable into the container. It will leverage the container lifecycle hooks to call the command right after the container is ready.

func WithAlwaysPull

func WithAlwaysPull() CustomizeDefinitionOption

WithAlwaysPull will pull the image before starting the container

func WithBridgeNetwork

func WithBridgeNetwork() CustomizeDefinitionOption

WithBridgeNetwork attachs a container to the "bridge" network. There is no need to set the network alias, as it is not supported for the "bridge" network.

func WithCmd

func WithCmd(cmd ...string) CustomizeDefinitionOption

WithCmd completely replaces the command for a container

func WithCmdArgs

func WithCmdArgs(cmdArgs ...string) CustomizeDefinitionOption

WithCmdArgs appends the command arguments to the command for a container

func WithConfigModifier

func WithConfigModifier(modifier func(config *container.Config)) CustomizeDefinitionOption

WithConfigModifier allows to override the default container config

func WithDockerClient

func WithDockerClient(dockerClient *client.Client) CustomizeDefinitionOption

WithDockerClient sets the docker client for a container

func WithEndpointSettingsModifier

func WithEndpointSettingsModifier(modifier func(settings map[string]*apinetwork.EndpointSettings)) CustomizeDefinitionOption

WithEndpointSettingsModifier allows to override the default endpoint settings

func WithEntrypoint

func WithEntrypoint(entrypoint ...string) CustomizeDefinitionOption

WithEntrypoint completely replaces the entrypoint of a container

func WithEntrypointArgs

func WithEntrypointArgs(entrypointArgs ...string) CustomizeDefinitionOption

WithEntrypointArgs appends the entrypoint arguments to the entrypoint of a container

func WithEnv

func WithEnv(envs map[string]string) CustomizeDefinitionOption

WithEnv sets the environment variables for a container. If the environment variable already exists, it will be overridden.

func WithExposedPorts

func WithExposedPorts(ports ...string) CustomizeDefinitionOption

WithExposedPorts appends the ports to the exposed ports for a container

func WithFiles

func WithFiles(files ...File) CustomizeDefinitionOption

WithFiles appends the files to the files for a container

func WithHostConfigModifier

func WithHostConfigModifier(modifier func(hostConfig *container.HostConfig)) CustomizeDefinitionOption

WithHostConfigModifier allows to override the default host config

func WithImage

func WithImage(image string) CustomizeDefinitionOption

WithImage sets the image for a container

func WithImagePlatform

func WithImagePlatform(platform string) CustomizeDefinitionOption

WithImagePlatform sets the platform for a container

func WithImageSubstitutors

func WithImageSubstitutors(fn ...ImageSubstitutor) CustomizeDefinitionOption

WithImageSubstitutors sets the image substitutors for a container

func WithLabels

func WithLabels(labels map[string]string) CustomizeDefinitionOption

WithLabels appends the labels to the labels for a container

func WithLifecycleHooks

func WithLifecycleHooks(hooks ...LifecycleHooks) CustomizeDefinitionOption

WithLifecycleHooks completely replaces the lifecycle hooks for a container

func WithLogConsumerConfig

func WithLogConsumerConfig(config *LogConsumerConfig) CustomizeDefinitionOption

WithLogConsumerConfig sets the log consumer config for a container. Beware that this option completely replaces the existing log consumer config, including the log consumers and the log production options, so it should be used with care.

func WithLogConsumers

func WithLogConsumers(consumer ...LogConsumer) CustomizeDefinitionOption

WithLogConsumers sets the log consumers for a container

func WithName

func WithName(containerName string) CustomizeDefinitionOption

WithName will set the name of the container.

func WithNetwork

func WithNetwork(aliases []string, nw *network.Network) CustomizeDefinitionOption

WithNetwork reuses an already existing network, attaching the container to it. Finally it sets the network alias on that network to the given alias.

func WithNetworkName

func WithNetworkName(aliases []string, networkName string) CustomizeDefinitionOption

WithNetworkName attachs a container to an already existing network, by its name. If the network is not "bridge", it sets the network alias on that network to the given alias, else, it returns an error. This is because network-scoped alias is supported only for containers in user defined networks.

func WithNewNetwork

func WithNewNetwork(ctx context.Context, aliases []string, opts ...network.Option) CustomizeDefinitionOption

WithNewNetwork creates a new network with random name and customizers, and attaches the container to it. Finally it sets the network alias on that network to the given alias.

func WithNoStart

func WithNoStart() CustomizeDefinitionOption

WithNoStart will prevent the container from being started after creation.

func WithStartupCommand

func WithStartupCommand(execs ...Executable) CustomizeDefinitionOption

WithStartupCommand will execute the command representation of each Executable into the container. It will leverage the container lifecycle hooks to call the command right after the container is started.

func WithWaitStrategy

func WithWaitStrategy(strategies ...wait.Strategy) CustomizeDefinitionOption

WithWaitStrategy replaces the wait strategy for a container, using 60 seconds as deadline

func WithWaitStrategyAndDeadline

func WithWaitStrategyAndDeadline(deadline time.Duration, strategies ...wait.Strategy) CustomizeDefinitionOption

WithWaitStrategyAndDeadline replaces the wait strategy for a container, including deadline

func (CustomizeDefinitionOption) Customize

func (opt CustomizeDefinitionOption) Customize(def *Definition) error

Customize implements the ContainerCustomizer interface.

type Definition

type Definition struct {
	// contains filtered or unexported fields
}

Definition is the Definition of a container.

func (*Definition) DockerClient

func (d *Definition) DockerClient() *client.Client

DockerClient returns the docker client used by the definition.

func (*Definition) Image

func (d *Definition) Image() string

Image returns the image used by the definition.

type DefinitionHook

type DefinitionHook func(ctx context.Context, def *Definition) error

DefinitionHook is a hook that will be called before a container is started. It can be used to modify the container definition on container creation, using the different lifecycle hooks that are available: - Building - Creating For that, it will receive a Definition, modify it and return an error if needed.

type Executable

type Executable interface {
	AsCommand() []string
	// Options can container two different types of options:
	// - Docker's ExecConfigs (WithUser, WithWorkingDir, WithEnv, etc.)
	// - testcontainers' ProcessOptions (i.e. Multiplexed response)
	Options() []exec.ProcessOption
}

Executable represents an executable command to be sent to a container, including options, as part of the different lifecycle hooks.

type File

type File struct {
	// Reader the reader to read the file from.
	// It takes precedence over [HostPath].
	Reader io.Reader

	// HostPath the path to the file on the host.
	// If [Reader] is not specified, the file will be read from the host path.
	HostPath string

	// ContainerPath the path to the file in the container.
	// Use the slash character that matches the path separator of the operating system
	// for the container.
	ContainerPath string

	// Mode the mode of the file
	Mode int64
}

File represents a file that will be copied when container starts

type FileFromContainer

type FileFromContainer struct {
	// contains filtered or unexported fields
}

FileFromContainer implements io.ReadCloser and tar.Reader for a single file in a container.

func (*FileFromContainer) Close

func (fc *FileFromContainer) Close() error

Close closes the file from the container.

func (*FileFromContainer) Read

func (fc *FileFromContainer) Read(b []byte) (int, error)

Read reads the file from the container.

type ImageSubstitutor

type ImageSubstitutor interface {
	// Description returns the name of the type and a short description of how it modifies the image.
	// Useful to be printed in logs
	Description() string
	Substitute(image string) (string, error)
}

ImageSubstitutor represents a way to substitute container image names

type LifecycleHooks

type LifecycleHooks struct {
	PreCreates     []DefinitionHook
	PostCreates    []ContainerHook
	PreStarts      []ContainerHook
	PostStarts     []ContainerHook
	PostReadies    []ContainerHook
	PreStops       []ContainerHook
	PostStops      []ContainerHook
	PreTerminates  []ContainerHook
	PostTerminates []ContainerHook
}

type Log

type Log struct {
	LogType string
	Content []byte
}

Log represents a message that was created by a process, LogType is either "STDOUT" or "STDERR", Content is the byte contents of the message itself

type LogConsumer

type LogConsumer interface {
	Accept(Log)
}

LogConsumer represents any object that can handle a Log. It is up to the LogConsumer instance what to do with the log.

type LogConsumerConfig

type LogConsumerConfig struct {
	// Opts the options for the production of logs
	Opts []LogProductionOption

	// Consumers the consumers for the logs. In case you need to have a thread-safe
	// consumer, you can use [NewThreadSafeLogConsumer] to wrap the consumer.
	Consumers []LogConsumer
}

LogConsumerConfig is a configuration object for the producer/consumer pattern

type LogProductionOption

type LogProductionOption func(*Container)

LogProductionOption is a function that modifies a Container.

func WithLogProductionTimeout

func WithLogProductionTimeout(timeout time.Duration) LogProductionOption

WithLogProductionTimeout is a functional option that sets the timeout for the log production. If the timeout is lower than 5s or greater than 60s it will be set to 5s or 60s respectively.

type StopOption

type StopOption func(*StopOptions)

StopOption is a type that represents an option for stopping a container.

func StopTimeout

func StopTimeout(timeout time.Duration) StopOption

StopTimeout returns a StopOption that sets the timeout. Default: See Container.Stop.

type StopOptions

type StopOptions struct {
	// contains filtered or unexported fields
}

StopOptions is a type that holds the options for stopping a container.

func NewStopOptions

func NewStopOptions(ctx context.Context, opts ...StopOption) *StopOptions

NewStopOptions returns a fully initialised StopOptions. Defaults: StopTimeout: 10 seconds.

func (*StopOptions) Context

func (o *StopOptions) Context() context.Context

Context returns the context to use during a Stop or Terminate.

func (*StopOptions) StopTimeout

func (o *StopOptions) StopTimeout() time.Duration

StopTimeout returns the stop timeout to use during a Stop or Terminate.

type TerminableContainer

type TerminableContainer interface {
	Terminate(ctx context.Context, opts ...TerminateOption) error
}

TerminableContainer is a container that can be terminated.

type TerminateOption

type TerminateOption func(*TerminateOptions)

TerminateOption is a type that represents an option for terminating a container.

func RemoveVolumes

func RemoveVolumes(volumes ...string) TerminateOption

RemoveVolumes returns a TerminateOption that sets additional volumes to remove. This is useful when the container creates named volumes that should be removed which are not removed by default. Default: nil.

func TerminateTimeout

func TerminateTimeout(timeout time.Duration) TerminateOption

TerminateTimeout returns a TerminateOption that sets the timeout. Default: See Container.Stop.

type TerminateOptions

type TerminateOptions struct {
	*StopOptions
	// contains filtered or unexported fields
}

TerminateOptions is a type that holds the options for terminating a container.

func NewTerminateOptions

func NewTerminateOptions(ctx context.Context, opts ...TerminateOption) *TerminateOptions

NewTerminateOptions returns a fully initialised TerminateOptions. Defaults: StopTimeout: 10 seconds.

func (*TerminateOptions) Cleanup

func (o *TerminateOptions) Cleanup(cli *client.Client) error

Cleanup performs any clean up needed

type ThreadSafeLogConsumer

type ThreadSafeLogConsumer struct {
	// contains filtered or unexported fields
}

ThreadSafeLogConsumer wraps a LogConsumer to make it thread-safe. It uses a mutex to protect the Accept method from concurrent access.

func NewThreadSafeLogConsumer

func NewThreadSafeLogConsumer(consumer LogConsumer) *ThreadSafeLogConsumer

NewThreadSafeLogConsumer creates a new thread-safe log consumer that wraps the given consumer.

func (*ThreadSafeLogConsumer) Accept

func (c *ThreadSafeLogConsumer) Accept(log Log)

Accept implements LogConsumer.Accept in a thread-safe way.

func (*ThreadSafeLogConsumer) Unwrap

func (c *ThreadSafeLogConsumer) Unwrap() LogConsumer

Unwrap returns the underlying LogConsumer.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL