goweb/middleware/container/service_container.go

50 lines
1.4 KiB
Go
Raw Permalink Normal View History

package container
2018-12-06 15:18:05 +01:00
import (
"context"
"errors"
"github.com/go-chi/chi/middleware"
2019-07-28 13:11:23 +02:00
goweb "gitlab.com/wpetit/goweb/middleware"
"gitlab.com/wpetit/goweb/service"
2018-12-06 15:18:05 +01:00
)
const (
// KeyServiceContainer is the context key associated with the ServiceContainer value
KeyServiceContainer goweb.ContextKey = "serviceContainer"
2018-12-06 15:18:05 +01:00
)
// ErrInvalidServiceContainer is returned when no service container
// could be found on the given context
var ErrInvalidServiceContainer = errors.New("invalid service container")
// From retrieves the service container from the given context
func From(ctx context.Context) (*service.Container, error) {
2018-12-06 15:18:05 +01:00
container, ok := ctx.Value(KeyServiceContainer).(*service.Container)
if !ok {
return nil, ErrInvalidServiceContainer
}
return container, nil
}
// Must retrieves the service container from the given context or panics otherwise
func Must(ctx context.Context) *service.Container {
container, err := From(ctx)
if err != nil {
panic(err)
}
return container
}
2018-12-06 15:18:05 +01:00
// ServiceContainer expose the given service container as a context value
// on the HTTP requests
func ServiceContainer(container *service.Container) goweb.Middleware {
2018-12-06 15:18:05 +01:00
return middleware.WithValue(KeyServiceContainer, container)
}
2020-07-07 08:19:51 +02:00
// WithContainer returns a new context.Context with the given *service.Container
// attached.
func WithContainer(ctx context.Context, container *service.Container) context.Context {
return context.WithValue(ctx, KeyServiceContainer, container)
}