goweb/middleware/container/service_container.go

44 lines
1.2 KiB
Go

package container
import (
"context"
"errors"
"github.com/go-chi/chi/middleware"
goweb "gitlab.com/wpetit/goweb/middleware"
"gitlab.com/wpetit/goweb/service"
)
const (
// KeyServiceContainer is the context key associated with the ServiceContainer value
KeyServiceContainer goweb.ContextKey = "serviceContainer"
)
// 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) {
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
}
// ServiceContainer expose the given service container as a context value
// on the HTTP requests
func ServiceContainer(container *service.Container) goweb.Middleware {
return middleware.WithValue(KeyServiceContainer, container)
}