my-log/formatters/new.go

41 lines
844 B
Go
Raw Normal View History

2024-03-07 10:10:54 -06:00
package formatters
import (
"context"
"fmt"
2024-03-07 10:10:54 -06:00
"codeberg.org/danjones000/my-log/config"
"github.com/spf13/viper"
2024-03-07 10:10:54 -06:00
)
type formatMaker func(config *viper.Viper) (Formatter, error)
2024-03-07 10:10:54 -06:00
var formatterMap = map[string]formatMaker{
"plain": newPlain,
2024-03-10 11:33:51 -05:00
"json": newJson,
2024-03-11 21:18:52 -05:00
"zero": newNull,
2024-03-07 10:10:54 -06:00
}
func Preferred(ctx context.Context) (f Formatter, err error) {
_, c := config.RetrieveFromContext(ctx)
return New(ctx, c.Formatters.Preferred)
2024-03-09 16:05:59 -06:00
}
func New(ctx context.Context, kind string) (f Formatter, err error) {
v, _ := config.RetrieveFromContext(ctx)
formatterConf := v.Sub("formatters." + kind)
2024-03-07 10:10:54 -06:00
if maker, ok := formatterMap[kind]; ok {
return maker(formatterConf)
2024-03-07 10:10:54 -06:00
}
return nil, fmt.Errorf("unimplemented format: %s", kind)
2024-03-07 10:10:54 -06:00
}
func Kinds() []string {
r := []string{}
for kind, _ := range formatterMap {
r = append(r, kind)
}
return r
}