refactor: docker engine with options

This commit is contained in:
Bo-Yi Wu 2022-08-13 14:30:05 +08:00 committed by Jason Song
parent 4eb5213294
commit 14a345504f
3 changed files with 45 additions and 18 deletions

View File

@ -137,8 +137,7 @@ func runDaemon(ctx context.Context, input *Input) func(cmd *cobra.Command, args
initLogging(cfg) initLogging(cfg)
opts := engine.Opts{} engine, err := engine.New()
engine, err := engine.NewEnv(opts)
if err != nil { if err != nil {
log.WithError(err). log.WithError(err).
Fatalln("cannot load the docker engine") Fatalln("cannot load the docker engine")
@ -161,7 +160,7 @@ func runDaemon(ctx context.Context, input *Input) func(cmd *cobra.Command, args
count++ count++
if count == 5 { if count == 5 {
log.WithError(err). log.WithError(err).
Fatalln("retry count reached") Fatalf("retry count reached: %d", count)
} }
time.Sleep(time.Second) time.Sleep(time.Second)
} else { } else {

View File

@ -6,30 +6,28 @@ import (
"github.com/docker/docker/client" "github.com/docker/docker/client"
) )
// Opts configures the Docker engine.
type Opts struct {
HidePull bool
}
type Docker struct { type Docker struct {
client client.APIClient client client.APIClient
hidePull bool hidePull bool
} }
func New(client client.APIClient, opts Opts) *Docker { func New(opts ...Option) (*Docker, error) {
return &Docker{
client: client,
hidePull: opts.HidePull,
}
}
// NewEnv returns a new Engine from the environment.
func NewEnv(opts Opts) (*Docker, error) {
cli, err := client.NewClientWithOpts(client.FromEnv) cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return New(cli, opts), nil
srv := &Docker{
client: cli,
}
// Loop through each option
for _, opt := range opts {
// Call the option giving the instantiated
opt.Apply(srv)
}
return srv, nil
} }
// Ping pings the Docker daemon. // Ping pings the Docker daemon.

30
engine/options.go Normal file
View File

@ -0,0 +1,30 @@
package engine
import "github.com/docker/docker/client"
// An Option configures a mutex.
type Option interface {
Apply(*Docker)
}
// OptionFunc is a function that configure a value.
type OptionFunc func(*Docker)
// Apply calls f(option)
func (f OptionFunc) Apply(docker *Docker) {
f(docker)
}
// WithClient set custom client
func WithClient(c client.APIClient) Option {
return OptionFunc(func(q *Docker) {
q.client = c
})
}
// WithHidePull set custom client
func WithHidePull(v bool) Option {
return OptionFunc(func(q *Docker) {
q.hidePull = v
})
}