chore: moved packages to v1

This commit is contained in:
abelith committed 2026-10-06 13:40:54 +03:00
1 parent 522ba1b639
commit 43e3a8a397
15 files changed
+26 -14

No files matched your search

+96
View File
@@ -0,0 +1,96 @@
package context
import (
"context"
"github.com/abelith/gomax/v1/state"
maxbot "github.com/max-messenger/max-bot-api-client-go/v2"
"github.com/max-messenger/max-bot-api-client-go/v2/model"
"time"
)
type Context struct {
ctx context.Context
upd model.Update
state *state.Context
api *maxbot.Api
}
type Option interface {
applyOption(opts *msgOptions)
}
type msgOptions struct {
kb *model.Keyboard
}
type responseOptionWrapper struct {
fn func(options *msgOptions)
}
func New(ctx context.Context, upd model.Update, state *state.Context, api *maxbot.Api) *Context {
return &Context{
ctx: ctx,
upd: upd,
state: state,
api: api,
}
}
func (c *Context) Context() context.Context {
return c.ctx
}
func (c *Context) SetContext(ctx context.Context) {
c.ctx = ctx
}
func (c *Context) State() *state.Context {
return c.state
}
func (c *Context) Update() model.Update {
return c.upd
}
func (c *Context) Respond(text string, opts ...Option) error {
msg := maxbot.NewMessage().
SetChat(c.upd.ChatID).
SetUser(c.upd.UserID).
SetText(text)
var cfg msgOptions
for _, opt := range opts {
opt.applyOption(&cfg)
}
if cfg.kb != nil {
msg.AddKeyboard(cfg.kb)
}
_, err := c.api.Messages.Send(c.ctx, msg)
return err
}
func (c *Context) Deadline() (deadline time.Time, ok bool) {
return c.ctx.Deadline()
}
func (c *Context) Done() <-chan struct{} {
return c.ctx.Done()
}
func (c *Context) Err() error {
return c.ctx.Err()
}
func (c *Context) Value(key any) any {
return c.ctx.Value(key)
}
func (w responseOptionWrapper) applyOption(cfg *msgOptions) {
w.fn(cfg)
}
func newOption(fn func(options *msgOptions)) Option {
return responseOptionWrapper{fn: fn}
}
+9
View File
@@ -0,0 +1,9 @@
package context
import "github.com/max-messenger/max-bot-api-client-go/v2/model"
func WithKeyboard(kb *model.Keyboard) Option {
return newOption(func(opts *msgOptions) {
opts.kb = kb
})
}
+191
View File
@@ -0,0 +1,191 @@
package core
import (
"context"
"errors"
mcontext "github.com/abelith/gomax/v1/context"
"github.com/abelith/gomax/v1/state"
"github.com/abelith/gomax/v1/state/memory"
maxbot "github.com/max-messenger/max-bot-api-client-go/v2"
"github.com/max-messenger/max-bot-api-client-go/v2/model"
"github.com/rs/zerolog/log"
"sync"
"time"
)
const (
defaultTTL = 5 * time.Second
)
type EventIsolation interface {
Lock(ctx context.Context, userID, chatID int) error
Unlock(ctx context.Context, userID, chatID int) error
}
type FSMStorage interface {
Get(ctx context.Context, userID int) (state.Snapshot, error)
Put(ctx context.Context, state state.Snapshot) error
Delete(ctx context.Context, userID int) error
}
type UpdateHandler interface {
HandleUpdate(c *mcontext.Context) error
Use(mw ...Middleware)
}
type Poller interface {
Start(ctx context.Context) (<-chan model.Update, error)
}
type DispatcherOption interface {
apply(d *dispatcherOptions)
}
type Dispatcher struct {
api *maxbot.Api
poller Poller
fsmStorage FSMStorage
eventIsolation EventIsolation
rt *Router
wg sync.WaitGroup
}
type dispatcherOptions struct {
poller Poller
fsmStorage FSMStorage
eventIsolation EventIsolation
}
type dispatcherOptionWrapper struct {
fn func(options *dispatcherOptions)
}
func NewDispatcher(api *maxbot.Api, options ...DispatcherOption) *Dispatcher {
d := &Dispatcher{
api: api,
rt: &Router{},
}
opts := newDispatcherOptions(api)
for _, opt := range options {
opt.apply(opts)
}
d.poller = opts.poller
d.fsmStorage = opts.fsmStorage
d.eventIsolation = opts.eventIsolation
return d
}
func (d *Dispatcher) HandleUpdate(c *mcontext.Context) error {
return d.rt.HandleUpdate(c)
}
func (d *Dispatcher) Use(mw ...Middleware) {
d.rt.Use(mw...)
}
func (d *Dispatcher) Start(ctx context.Context) error {
ch, err := d.poller.Start(ctx)
if err != nil {
return err
}
d.handleUpdates(ch)
<-ctx.Done()
d.wg.Wait()
return nil
}
func (d *Dispatcher) handleUpdates(ch <-chan model.Update) {
for upd := range ch {
d.wg.Go(func() {
ctx := context.Background()
_ = d.eventIsolation.Lock(ctx, int(upd.UserID), int(upd.ChatID)) // todo: handle error somehow (retry or smth)
defer func() {
err := d.eventIsolation.Unlock(ctx, int(upd.UserID), int(upd.ChatID))
if err != nil {
log.Warn().
Err(err).
Int64("user_id", upd.UserID).
Int64("chat_id", upd.ChatID).
Msg("failed to unlock on update")
}
}()
d.handleUpdate(ctx, upd)
})
}
}
func (d *Dispatcher) handleUpdate(ctx context.Context, upd model.Update) {
var st *state.Context
snapshot, err := d.fsmStorage.Get(ctx, int(upd.UserID))
if err != nil && !errors.Is(err, state.ErrStateNotFound) {
log.Error().Err(err).Send()
return
}
if errors.Is(err, state.ErrStateNotFound) {
st = state.New(int(upd.UserID))
} else {
st = state.Restore(snapshot)
}
c := mcontext.New(ctx, upd, st, d.api)
if err := d.rt.HandleUpdate(c); err != nil {
log.Error().Err(err).Send()
return
}
st = c.State()
if st.State() == state.ClearState {
if err := d.fsmStorage.Delete(ctx, int(upd.UserID)); err != nil {
log.Error().Err(err).Send()
return
}
}
if st.State() != "" {
if err := d.fsmStorage.Put(ctx, st.Snapshot()); err != nil {
log.Error().Err(err).Send()
return
}
}
}
func WithPoller(poller Poller) DispatcherOption {
return newOption(func(opts *dispatcherOptions) {
opts.poller = poller
})
}
func WithFSMStorage(storage FSMStorage) DispatcherOption {
return newOption(func(opts *dispatcherOptions) {
opts.fsmStorage = storage
})
}
func WithEventIsolation(eventIsolation EventIsolation) DispatcherOption {
return newOption(func(opts *dispatcherOptions) {
opts.eventIsolation = eventIsolation
})
}
func newDispatcherOptions(api *maxbot.Api) *dispatcherOptions {
return &dispatcherOptions{
poller: NewLongPoller(api),
fsmStorage: memory.NewFSMStorage(),
eventIsolation: memory.NewEventIsolation(defaultTTL),
}
}
func newOption(fn func(options *dispatcherOptions)) DispatcherOption {
return dispatcherOptionWrapper{fn: fn}
}
func (dow dispatcherOptionWrapper) apply(opts *dispatcherOptions) {
dow.fn(opts)
}
+7
View File
@@ -0,0 +1,7 @@
package core
import "fmt"
var (
ErrRouteNotFound = fmt.Errorf("route not foun")
)
+13
View File
@@ -0,0 +1,13 @@
package core
import mcontext "github.com/abelith/gomax/v1/context"
type HandlerFunc func(c *mcontext.Context) error
func (h HandlerFunc) HandleUpdate(c *mcontext.Context) error {
return h(c)
}
func (h HandlerFunc) Use(_ ...Middleware) {
panic("HandlerFunc.Use must never be called")
}
+264
View File
@@ -0,0 +1,264 @@
package core
import (
"context"
"crypto/tls"
"errors"
"fmt"
maxbot "github.com/max-messenger/max-bot-api-client-go/v2"
"github.com/max-messenger/max-bot-api-client-go/v2/model"
"github.com/rs/zerolog/log"
"net"
"net/http"
"time"
)
const (
defaultInterval = 200 * time.Millisecond
defaultWhStartTimeout = 10 * time.Second
)
type WebhookOption interface {
apply(opts *webhookOptions)
}
type LongPollerOption interface {
apply(opts *longPollerOptions)
}
type Webhook struct {
srv *http.Server
ch chan model.Update
}
type LongPoller struct {
api *maxbot.Api
pollInterval time.Duration
}
type TestPoller struct{}
type webhookOptions struct {
addr string
tlsConfig *tls.Config
readTimeout time.Duration
readHeaderTimeout time.Duration
writeTimeout time.Duration
idleTimeout time.Duration
maxHeaderBytes int
baseContext func(l net.Listener) context.Context
connContext func(ctx context.Context, conn net.Conn) context.Context
}
type longPollerOptions struct {
pollInterval time.Duration
}
type webhookOptionWrapper struct {
fn func(opts *webhookOptions)
}
func NewWebhookPoller(api *maxbot.Api, secret string, options ...WebhookOption) *Webhook {
ch := make(chan model.Update, 1)
handler := api.GetHandler(func(ctx context.Context, update model.Update) {
select {
case ch <- update:
case <-ctx.Done():
}
}, secret)
srv := &http.Server{
Handler: handler,
}
wh := &Webhook{
srv: srv,
ch: ch,
}
opts := newWebhookOptions()
for _, opt := range options {
opt.apply(opts)
}
wh.srv.Addr = opts.addr
wh.srv.TLSConfig = opts.tlsConfig
wh.srv.ReadTimeout = opts.readTimeout
wh.srv.ReadHeaderTimeout = opts.readHeaderTimeout
wh.srv.WriteTimeout = opts.writeTimeout
wh.srv.IdleTimeout = opts.idleTimeout
wh.srv.MaxHeaderBytes = opts.maxHeaderBytes
wh.srv.BaseContext = opts.baseContext
wh.srv.ConnContext = opts.connContext
return wh
}
func (w *Webhook) Start(_ context.Context) (<-chan model.Update, error) {
errCh := make(chan error, 1)
defer close(errCh)
go func() {
var err error
defer func() {
errCh <- err
if err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal().Err(err).Msg("webhook server error")
}
}()
if w.srv.TLSConfig == nil {
err = w.srv.ListenAndServe()
return
}
err = w.srv.ListenAndServeTLS("", "")
}()
select {
case err := <-errCh:
return nil, err
case <-time.After(defaultWhStartTimeout):
return w.ch, nil
}
}
func (w *Webhook) Stop(ctx context.Context) error {
return w.srv.Shutdown(ctx)
}
func NewLongPoller(api *maxbot.Api, options ...LongPollerOption) *LongPoller {
lp := &LongPoller{
api: api,
}
opts := newLongPollerOptions()
for _, opt := range options {
opt.apply(opts)
}
lp.pollInterval = opts.pollInterval
return lp
}
func (lp *LongPoller) Start(ctx context.Context) (<-chan model.Update, error) {
var updates []model.Update
var marker int64
var err error
ch := make(chan model.Update)
go func() {
defer close(ch)
// todo: backoff on errors
for {
select {
case <-ctx.Done():
return
case <-time.Tick(lp.pollInterval):
start := time.Now()
updates, marker, err = lp.api.Subscriptions.GetUpdates(ctx, marker)
latency := time.Since(start)
if err != nil && !errors.Is(err, context.Canceled) {
log.Error().Err(err).Send()
}
log.Ctx(ctx).Debug().
Int("received", len(updates)).
Dur("latency", latency).
Msg("received updates")
for _, update := range updates {
select {
case <-ctx.Done():
return
case ch <- update:
}
}
}
}
}()
return ch, nil
}
func (tp *TestPoller) Start(_ context.Context) (<-chan model.Update, error) {
return nil, fmt.Errorf("unimplemented")
}
func WithAddress(addr string) WebhookOption {
return newWhOption(func(opts *webhookOptions) {
opts.addr = addr
})
}
func WithTLSConfig(cfg *tls.Config) WebhookOption {
return newWhOption(func(opts *webhookOptions) {
opts.tlsConfig = cfg
})
}
func WithReadTimeout(timeout time.Duration) WebhookOption {
return newWhOption(func(opts *webhookOptions) {
opts.readTimeout = timeout
})
}
func WithReadHeaderTimeout(timeout time.Duration) WebhookOption {
return newWhOption(func(opts *webhookOptions) {
opts.readHeaderTimeout = timeout
})
}
func WithWriteTimeout(timeout time.Duration) WebhookOption {
return newWhOption(func(opts *webhookOptions) {
opts.writeTimeout = timeout
})
}
func WithIdleTimeout(timeout time.Duration) WebhookOption {
return newWhOption(func(opts *webhookOptions) {
opts.idleTimeout = timeout
})
}
func WithMaxHeaderBytes(bytes int) WebhookOption {
return newWhOption(func(opts *webhookOptions) {
opts.maxHeaderBytes = bytes
})
}
func WithBaseContext(fn func(l net.Listener) context.Context) WebhookOption {
return newWhOption(func(opts *webhookOptions) {
opts.baseContext = fn
})
}
func WithConnContext(fn func(ctx context.Context, c net.Conn) context.Context) WebhookOption {
return newWhOption(func(opts *webhookOptions) {
opts.connContext = fn
})
}
func newLongPollerOptions() *longPollerOptions {
return &longPollerOptions{
pollInterval: defaultInterval,
}
}
func newWebhookOptions() *webhookOptions {
return &webhookOptions{
addr: ":8080",
}
}
func newWhOption(fn func(options *webhookOptions)) WebhookOption {
return webhookOptionWrapper{fn: fn}
}
func (wow webhookOptionWrapper) apply(opts *webhookOptions) {
wow.fn(opts)
}
+70
View File
@@ -0,0 +1,70 @@
package core
import (
"errors"
mcontext "github.com/abelith/gomax/v1/context"
)
type Middleware func(next HandlerFunc) HandlerFunc
type route struct {
h UpdateHandler
filters []func(c *mcontext.Context) bool
}
type Router struct {
routes []route
mw []Middleware
}
func (r *Router) HandleUpdate(c *mcontext.Context) error {
var current HandlerFunc = r.dispatch
for i := len(r.mw) - 1; i >= 0; i-- {
current = r.mw[i](current)
}
return current.HandleUpdate(c)
}
func (r *Router) Use(mws ...Middleware) {
r.mw = append(r.mw, mws...)
}
func (r *Router) HandleFunc(h HandlerFunc, filters ...func(c *mcontext.Context) bool) {
r.routes = append(r.routes, route{
h: h,
filters: filters,
})
}
func (r *Router) Handle(h UpdateHandler, filters ...func(c *mcontext.Context) bool) {
r.routes = append(r.routes, route{
h: h,
filters: filters,
})
}
func (r *Router) dispatch(c *mcontext.Context) error {
for _, rt := range r.routes {
if match(rt.filters, c) {
err := rt.h.HandleUpdate(c)
if errors.Is(err, ErrRouteNotFound) {
continue
}
return err
}
}
return ErrRouteNotFound
}
func match(filters []func(c *mcontext.Context) bool, c *mcontext.Context) bool {
for _, filter := range filters {
if !filter(c) {
return false
}
}
return true
}
+17
View File
@@ -0,0 +1,17 @@
package errors
type GomaxError struct {
Message string
Err error
}
func (ge *GomaxError) Error() string {
return ge.Err.Error()
}
func New(parent error, text string) error {
return &GomaxError{
Message: text,
Err: parent,
}
}
+132
View File
@@ -0,0 +1,132 @@
package filters
import (
mcontext "github.com/abelith/gomax/v1/context"
"github.com/abelith/gomax/v1/state"
"github.com/max-messenger/max-bot-api-client-go/v2/model"
"regexp"
"strings"
)
type Filter func(c *mcontext.Context) bool
type CallbackFilter Filter
type MessageFilter Filter
func And(filters ...func(c *mcontext.Context) bool) func(c *mcontext.Context) bool {
return func(c *mcontext.Context) bool {
for _, filter := range filters {
if !filter(c) {
return false
}
}
return true
}
}
func Or(filters ...func(c *mcontext.Context) bool) func(c *mcontext.Context) bool {
return func(c *mcontext.Context) bool {
for _, filter := range filters {
if filter(c) {
return true
}
}
return false
}
}
func StartCommand() Filter {
return func(c *mcontext.Context) bool {
upd := c.Update()
if upd.UpdateType == model.UpdateBotStarted {
return true
}
return strings.HasPrefix(upd.GetCommand().Command, "/start")
}
}
func Command(cmd string) Filter {
return func(c *mcontext.Context) bool {
upd := c.Update()
return upd.UpdateType == model.UpdateMessageCreated && strings.HasPrefix(upd.GetCommand().Command, cmd)
}
}
func State(state state.State) Filter {
return func(c *mcontext.Context) bool {
return c.State().State() == state
}
}
func BotStopped() Filter {
return func(c *mcontext.Context) bool {
return c.Update().UpdateType == model.UpdateBotStopped
}
}
func Message() MessageFilter {
return func(c *mcontext.Context) bool {
return c.Update().UpdateType == model.UpdateMessageCreated && c.Update().Message != nil
}
}
func (mf MessageFilter) Text(s string) MessageFilter {
return func(c *mcontext.Context) bool {
if !mf(c) {
return false
}
return c.Update().Message.Body.Text == s
}
}
func (mf MessageFilter) Regex(re *regexp.Regexp) MessageFilter {
return func(c *mcontext.Context) bool {
if !mf(c) {
return false
}
return re.MatchString(c.Update().Message.Body.Text)
}
}
func (mf MessageFilter) Geo() MessageFilter {
return func(c *mcontext.Context) bool {
if !mf(c) {
return false
}
for _, attachment := range c.Update().Message.Body.Attachments {
if attachment.Type == model.AttachLocation {
return true
}
}
return false
}
}
func Callback() CallbackFilter {
return func(c *mcontext.Context) bool {
return c.Update().UpdateType == model.UpdateMessageCallback
}
}
func (cf CallbackFilter) StartsWith(prefix string) CallbackFilter {
return func(c *mcontext.Context) bool {
if !cf(c) {
return false
}
upd := c.Update().Callback
if upd == nil {
return false
}
return strings.HasPrefix(upd.Payload, prefix)
}
}
+1
View File
@@ -0,0 +1 @@
package v1
+59
View File
@@ -0,0 +1,59 @@
package middleware
import (
"errors"
mcontext "github.com/abelith/gomax/v1/context"
"github.com/abelith/gomax/v1/core"
merrors "github.com/abelith/gomax/v1/errors"
"github.com/rs/zerolog/log"
)
func MwErrorResponder(defaultMsg string) core.Middleware {
return func(next core.HandlerFunc) core.HandlerFunc {
return func(c *mcontext.Context) error {
err := next.HandleUpdate(c)
var maxErr *merrors.GomaxError
if errors.As(err, &maxErr) {
return c.Respond(maxErr.Message)
}
if err != nil {
return c.Respond(defaultMsg)
}
return nil
}
}
}
func MwLoggerInjector() core.Middleware {
return func(next core.HandlerFunc) core.HandlerFunc {
return func(c *mcontext.Context) error {
ctx := log.Logger.With().Int64("user_id", c.Update().UserID).
Logger().WithContext(c.Context())
c.SetContext(ctx)
return next.HandleUpdate(c)
}
}
}
func MwDebugState() core.Middleware {
return func(next core.HandlerFunc) core.HandlerFunc {
return func(c *mcontext.Context) error {
log.Debug().Any("state", c.State()).Any("update", c.Update()).Send()
return next.HandleUpdate(c)
}
}
}
func MwErrorLogger() core.Middleware {
return func(next core.HandlerFunc) core.HandlerFunc {
return func(c *mcontext.Context) error {
if err := next.HandleUpdate(c); err != nil {
log.Ctx(c).Err(err).Send()
return err
}
return nil
}
}
}
+110
View File
@@ -0,0 +1,110 @@
package memory
import (
"context"
"github.com/abelith/gomax/v1/state"
"sync"
"time"
)
type FSMStorage struct {
m sync.Map
}
type EventIsolation struct {
mu sync.Mutex
locks map[eventIsolationKey]*lockEntry
ttl time.Duration
}
type eventIsolationKey struct {
userID int
chatID int
}
type lockEntry struct {
timer *time.Timer
done chan struct{}
}
func NewFSMStorage() *FSMStorage {
return &FSMStorage{}
}
func (f *FSMStorage) Get(_ context.Context, userID int) (state.Snapshot, error) {
st, ok := f.m.Load(userID)
if !ok {
return state.Snapshot{}, state.ErrStateNotFound
}
return st.(state.Snapshot), nil
}
func (f *FSMStorage) Put(_ context.Context, snapshot state.Snapshot) error {
f.m.Store(snapshot.ID, snapshot)
return nil
}
func (f *FSMStorage) Delete(_ context.Context, userID int) error {
f.m.Delete(userID)
return nil
}
func NewEventIsolation(ttl time.Duration) *EventIsolation {
return &EventIsolation{
locks: make(map[eventIsolationKey]*lockEntry),
ttl: ttl,
}
}
func (ei *EventIsolation) Lock(ctx context.Context, userID, chatID int) error {
key := eventIsolationKey{userID: userID, chatID: chatID}
for {
ei.mu.Lock()
entry, busy := ei.locks[key]
if !busy {
ei.acquireLocked(key)
ei.mu.Unlock()
return nil
}
done := entry.done
ei.mu.Unlock()
select {
case <-done:
case <-ctx.Done():
return ctx.Err()
}
}
}
func (ei *EventIsolation) Unlock(_ context.Context, userID, chatID int) error {
key := eventIsolationKey{userID: userID, chatID: chatID}
ei.mu.Lock()
defer ei.mu.Unlock()
if entry, ok := ei.locks[key]; ok {
ei.releaseLocked(key, entry)
}
return nil
}
func (ei *EventIsolation) acquireLocked(key eventIsolationKey) {
entry := &lockEntry{done: make(chan struct{})}
entry.timer = time.AfterFunc(ei.ttl, func() {
ei.mu.Lock()
defer ei.mu.Unlock()
if cur, ok := ei.locks[key]; ok && cur == entry {
ei.releaseLocked(key, entry)
}
})
ei.locks[key] = entry
}
func (ei *EventIsolation) releaseLocked(key eventIsolationKey, entry *lockEntry) {
entry.timer.Stop()
delete(ei.locks, key)
close(entry.done)
}
+198
View File
@@ -0,0 +1,198 @@
package state
import (
"encoding/json"
"fmt"
"github.com/rs/zerolog/log"
)
var (
ErrStateNotFound = fmt.Errorf("state not found")
ErrKeyNotFound = fmt.Errorf("state: key not found")
)
const ClearState State = "clear"
type State string
type Codec interface {
Marshal(v any) ([]byte, error)
Unmarshal(data []byte, v any) error
}
type JSONCodec struct{}
func (JSONCodec) Marshal(v any) ([]byte, error) {
return json.Marshal(v)
}
func (JSONCodec) Unmarshal(d []byte, v any) error {
return json.Unmarshal(d, v)
}
type Snapshot struct {
ID int `json:"id"`
State State `json:"state"`
Data map[string][]byte `json:"data"`
}
type Context struct {
id int
state State
data map[string][]byte
codec Codec
}
type Option func(*Context)
func WithCodec(c Codec) Option { return func(sc *Context) { sc.codec = c } }
func New(id int, opts ...Option) *Context {
sc := &Context{
id: id,
data: make(map[string][]byte),
codec: JSONCodec{},
}
for _, o := range opts {
o(sc)
}
return sc
}
func Restore(s Snapshot, opts ...Option) *Context {
sc := New(s.ID, opts...)
sc.state = s.State
for k, v := range s.Data {
sc.data[k] = v
}
return sc
}
func (sc *Context) Snapshot() Snapshot {
data := make(map[string][]byte, len(sc.data))
for k, v := range sc.data {
data[k] = v
}
return Snapshot{ID: sc.id, State: sc.state, Data: data}
}
func (sc *Context) Set(state State) {
log.Debug().
Int("user_id", sc.id).
Str("from", string(sc.state)).
Str("to", string(state)).
Msg("fsm state transition")
sc.state = state
}
func (sc *Context) State() State { return sc.state }
func (sc *Context) Clear() {
sc.state = ClearState
sc.data = make(map[string][]byte)
}
func (sc *Context) Store(key string, val any) error {
b, err := sc.codec.Marshal(val)
if err != nil {
return fmt.Errorf("sc.Store: failed to encode %q: %w", key, err)
}
sc.data[key] = b
return nil
}
func (sc *Context) Delete(key string) {
delete(sc.data, key)
}
func (sc *Context) Load(key string) Value {
b, ok := sc.data[key]
return Value{key: key, raw: b, ok: ok, codec: sc.codec}
}
type Value struct {
key string
raw []byte
ok bool
codec Codec
}
func (v Value) Exists() bool { return v.ok }
func (v Value) Raw() []byte { return v.raw }
func (v Value) Decode(dst any) error {
if !v.ok {
return fmt.Errorf("%w: %q", ErrKeyNotFound, v.key)
}
if err := v.codec.Unmarshal(v.raw, dst); err != nil {
return fmt.Errorf("state: decode %q as %T: %w", v.key, dst, err)
}
return nil
}
func (v Value) Str() (string, error) {
var s string
if err := v.Decode(&s); err != nil {
return "", err
}
return s, nil
}
func (v Value) Int() (int, error) {
var i int
if err := v.Decode(&i); err != nil {
return 0, err
}
return i, nil
}
func (v Value) Bool() (bool, error) {
var b bool
if err := v.Decode(&b); err != nil {
return false, err
}
return b, nil
}
func (v Value) Float() (float64, error) {
var f float64
if err := v.Decode(&f); err != nil {
return 0, err
}
return f, nil
}
func (v Value) Bytes() ([]byte, error) {
var b []byte
if err := v.Decode(&b); err != nil {
return nil, err
}
return b, nil
}
func (v Value) StrOr(def string) string {
if s, err := v.Str(); err == nil {
return s
}
return def
}
func (v Value) IntOr(def int) int {
if i, err := v.Int(); err == nil {
return i
}
return def
}
func (v Value) BoolOr(def bool) bool {
if b, err := v.Bool(); err == nil {
return b
}
return def
}
func (v Value) FloatOr(def float64) float64 {
if f, err := v.Float(); err == nil {
return f
}
return def
}