Files
2026-11-06 16:58:42 +08:00

48 lines
1.2 KiB
Go

package discovery
import (
"errors"
"strings"
"time"
clientv3 "go.etcd.io/etcd/client/v3"
)
type Config struct {
Endpoints []string `mapstructure:"endpoints"`
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
DialTimeout time.Duration `mapstructure:"dial_timeout"`
}
func (cfg Config) Validate() error {
if len(cfg.Endpoints) == 0 || cfg.DialTimeout <= 0 {
return errors.New("etcd endpoints and positive dial_timeout are required")
}
for _, endpoint := range cfg.Endpoints {
if strings.TrimSpace(endpoint) == "" {
return errors.New("etcd endpoints must not be empty")
}
}
return nil
}
func NewClient(cfg Config) (*clientv3.Client, error) {
if err := cfg.Validate(); err != nil {
return nil, err
}
return clientv3.New(clientv3.Config{
Endpoints: cfg.Endpoints,
Username: cfg.Username,
Password: cfg.Password,
DialTimeout: cfg.DialTimeout,
})
}
func ValidateService(service string) error {
if strings.TrimSpace(service) == "" || strings.ContainsAny(service, "/:?# \t\r\n") {
return errors.New("service name must be a non-empty name without URL separators or whitespace")
}
return nil
}