rebound/options.go

84 lines
1.8 KiB
Go

package rebound
import (
"log"
"time"
"forge.cadoles.com/wpetit/rebound/http"
"forge.cadoles.com/wpetit/rebound/ssh"
"github.com/caarlos0/env/v9"
"github.com/pkg/errors"
)
type Options struct {
Address string `env:"REBOUND_ADDRESS"`
StatsFile string `env:"REBOUND_STATS_FILE"`
StatsFileSaveInterval time.Duration `env:"REBOUND_STATS_FILE_SAVE_INTERVAL"`
Logger func(message string, args ...any)
SSH *ssh.Options `envPrefix:"REBOUND_SSH_"`
HTTP *http.Options `envPrefix:"REBOUND_HTTP_"`
}
func (o *Options) ParseEnv() error {
if err := env.Parse(o); err != nil {
return errors.WithStack(err)
}
return nil
}
type OptionFunc func(*Options)
func DefaultOptions() *Options {
return &Options{
Address: "127.0.0.1:2222",
StatsFile: "stats.json",
StatsFileSaveInterval: 30 * time.Second,
Logger: log.Printf,
SSH: ssh.DefaultOptions(),
HTTP: http.DefaultOptions(),
}
}
func WithAddress(addr string) func(*Options) {
return func(opts *Options) {
opts.Address = addr
}
}
func WithLogger(logger func(message string, args ...any)) func(*Options) {
return func(opts *Options) {
opts.Logger = logger
opts.SSH.Logger = logger
opts.HTTP.Logger = logger
}
}
func WithStatsFile(path string) func(*Options) {
return func(o *Options) {
o.StatsFile = path
}
}
func WithStatsFileSaveInterval(interval time.Duration) func(*Options) {
return func(o *Options) {
o.StatsFileSaveInterval = interval
}
}
func WithSSHOption(funcs ...ssh.OptionFunc) func(*Options) {
return func(o *Options) {
for _, fn := range funcs {
fn(o.SSH)
}
}
}
func WitHTTPOption(funcs ...http.OptionFunc) func(*Options) {
return func(o *Options) {
for _, fn := range funcs {
fn(o.HTTP)
}
}
}