2018-12-07 10:13:53 +01:00
|
|
|
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
|
2018-12-07 10:13:53 +01:00
|
|
|
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")
|
|
|
|
|
2018-12-07 10:13:53 +01:00
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|
2018-12-07 10:13:53 +01:00
|
|
|
// 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
|
2018-12-07 10:13:53 +01:00
|
|
|
func ServiceContainer(container *service.Container) goweb.Middleware {
|
2018-12-06 15:18:05 +01:00
|
|
|
return middleware.WithValue(KeyServiceContainer, container)
|
|
|
|
}
|