Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions server/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,23 @@ func WithSession(secret, name string, options ...session.Option) Option {
}
}

// WithAssets allows to serve embedded assets from a given
// embedded filesystem at a specified serving path. It sets up
// three context values: "assetManager", "assetPath", and "importMap".
// These values can be used by other components to manage and serve
// assets efficiently.
func WithAssets(embedded fs.FS, servingPath string) Option {
manager := assets.NewManager(embedded, servingPath)
return func(m *mux) {
m.Use(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// finding the valuer from the context
vlr := ValuerFromContext(r.Context())
if vlr != nil {
// retrieving the valuer from the context
vlr, ok := r.Context().Value(valuerContextKey).(interface {
Set(string, any)
})

// setting values in the context valuer
if ok {
vlr.Set("assetManager", manager)
vlr.Set("assetPath", manager.PathFor)
vlr.Set("importMap", manager.ImportMap)
Expand Down
14 changes: 4 additions & 10 deletions server/valuer.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,12 @@ const (
valuerContextKey = "valuer"
)

// Valuer interface to store and retrieve values from the request context
// these values can be used by other components such as the render engine
// or the assets manager.
type Valuer interface {
Values() map[string]any
Value(string) any
Set(string, any)
type valueReader interface {
Value(key string) any
}

// ValuerFromContext retrieves the Valuer from the context.
func ValuerFromContext(ctx context.Context) Valuer {
vlr, ok := ctx.Value(valuerContextKey).(Valuer)
func Valuer(ctx context.Context) valueReader {
vlr, ok := ctx.Value(valuerContextKey).(valueReader)
if !ok {
return nil
}
Expand Down
Loading