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) } // 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) }