sshpoke/internal/config/model.go

85 lines
1.9 KiB
Go
Raw Normal View History

2023-11-16 20:09:40 +03:00
package config
import (
"net/http"
"path/filepath"
"github.com/docker/docker/client"
"github.com/docker/go-connections/tlsconfig"
)
var DefaultConfig Config
type Config struct {
Debug bool `mapstructure:"debug"`
Docker DockerConfig `mapstructure:"docker"`
}
type DockerConfig struct {
FromEnv bool `mapstructure:"from_env"`
CertPath string `mapstructure:"cert_path"`
TLSVerify *bool `mapstructure:"tls_verify,omitempty"`
Host string `mapstructure:"host"`
Version string `mapstructure:"version"`
}
func (d DockerConfig) Opts(c *client.Client) error {
if d.FromEnv {
return client.FromEnv(c)
}
ops := []client.Opt{
d.withTLSClientConfig(),
d.withHost(),
d.withVersion(),
}
for _, op := range ops {
if err := op(c); err != nil {
return err
}
}
return nil
}
func (d DockerConfig) withTLSClientConfig() client.Opt {
return func(c *client.Client) error {
dockerCertPath := d.CertPath
if dockerCertPath == "" {
return nil
}
skipTLSVerify := false
if d.TLSVerify != nil && !(*d.TLSVerify) {
skipTLSVerify = true
}
options := tlsconfig.Options{
CAFile: filepath.Join(dockerCertPath, "ca.pem"),
CertFile: filepath.Join(dockerCertPath, "cert.pem"),
KeyFile: filepath.Join(dockerCertPath, "key.pem"),
InsecureSkipVerify: skipTLSVerify,
}
tlsConfig, err := tlsconfig.Client(options)
if err != nil {
return err
}
return client.WithHTTPClient(&http.Client{
Transport: &http.Transport{TLSClientConfig: tlsConfig},
CheckRedirect: client.CheckRedirect,
})(c)
}
}
func (d DockerConfig) withHost() client.Opt {
return func(c *client.Client) error {
if host := d.Host; host != "" {
return client.WithHost(host)(c)
}
return nil
}
}
func (d DockerConfig) withVersion() client.Opt {
return func(c *client.Client) error {
return client.WithVersion(d.Version)(c)
}
}