Split run and logs

This commit is contained in:
nemunaire 2021-05-02 16:26:23 +02:00
commit 539cbd68a9
4 changed files with 56 additions and 13 deletions

View file

@ -11,8 +11,12 @@ import (
oci "github.com/opencontainers/image-spec/specs-go/v1"
)
func newCli() (*client.Client, error) {
return client.NewClientWithOpts(client.FromEnv)
}
func Ps() ([]types.Container, error) {
cli, err := client.NewClientWithOpts(client.FromEnv)
cli, err := newCli()
if err != nil {
return nil, err
}
@ -25,10 +29,10 @@ func Ps() ([]types.Container, error) {
return containers, nil
}
func RunHello() (io.ReadCloser, error) {
cli, err := client.NewClientWithOpts(client.FromEnv)
func Run(image string) (string, error) {
cli, err := newCli()
if err != nil {
return nil, err
return "", err
}
ctnr, err := cli.ContainerCreate(
@ -36,7 +40,7 @@ func RunHello() (io.ReadCloser, error) {
&container.Config{
AttachStdout: true,
AttachStderr: true,
Image: "hello-world",
Image: image,
},
&container.HostConfig{},
&network.NetworkingConfig{},
@ -47,15 +51,24 @@ func RunHello() (io.ReadCloser, error) {
"",
)
if err != nil {
return nil, err
return "", err
}
err = cli.ContainerStart(context.Background(), ctnr.ID, types.ContainerStartOptions{})
if err != nil {
return "", err
}
return ctnr.ID, nil
}
func Logs(id string) (io.ReadCloser, error) {
cli, err := newCli()
if err != nil {
return nil, err
}
return cli.ContainerLogs(context.Background(), ctnr.ID, types.ContainerLogsOptions{
return cli.ContainerLogs(context.Background(), id, types.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
Follow: true,