options.go

60 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
package application

import "io/fs"

// Option configures the application
type Option func(*App)

// WithEmailer sets the emailer implementation
func WithEmailer(emailer Emailer) Option {
	return func(app *App) {
		app.Emailer = emailer
	}
}

// WithFunc registers a template function
func WithFunc(name string, fn any) Option {
	return func(app *App) {
		app.Func(name, fn)
	}
}

// WithValue registers a template function that returns the given value
func WithValue(name string, value any) Option {
	return func(app *App) {
		app.funcs[name] = func() any { return value }
	}
}

// WithController registers a controller with the application.
// Takes (name, controller) from factory function like controllers.Home().
func WithController(name string, controller Controller) Option {
	return func(app *App) {
		app.Controller(name, controller)
	}
}

// WithMiddleware adds a middleware to the handler chain.
// Middlewares are applied in order, with the last-added wrapping outermost.
func WithMiddleware(mw Middleware) Option {
	return func(app *App) {
		app.middlewares = append(app.middlewares, mw)
	}
}

// WithHealthPath sets the path for the auto-registered health endpoint.
// Defaults to "/health" if not set.
func WithHealthPath(path string) Option {
	return func(app *App) {
		app.healthPath = path
	}
}

// WithViews sets the views filesystem for the application.
// This is primarily used for testing; production code should use Serve().
func WithViews(views fs.FS) Option {
	return func(app *App) {
		app.viewsFS = views
		app.base = app.parseBaseTemplates(views)
	}
}