vroomy

package module
v0.21.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 25 Imported by: 13 modules, 30 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Vroomy   GoDoc Coverage Lint MIT licensed Contributors

Vroomy billboard

Vroomy is a Go library for building HTTP/HTTPS services from registered plugins. Plugins provide request handlers and shared backends; TOML config defines routes, groups, environment values, and listeners. Plugins are compiled into your application.

Quickstart

Use Go 1.27.2 or newer (see go.mod). From a checkout of this repository:

go mod download
go run ./examples/hello config.example.toml

In another terminal:

curl --fail http://localhost:8080/
curl --fail http://localhost:8080/api/ping

Both return PONG followed by a newline. Stop the server with Ctrl-C. The example creates ./data; copy the config and change port if 8080 is already in use.

The example keeps each plugin in its own file under the application's plugins directory:

examples/hello/
├── main.go
└── plugins/
    └── hello.go

main.go blank-imports the plugins package, which runs the init() function in plugins/hello.go. That function calls vroomy.Register("hello", &helloPlugin{}) before main starts. The application then loads config.example.toml. It needs no external plugins or certificates. A minimal configuration for that plugin is:

dir = "."
port = 8080

[env]
dataDir = "./data"

[[route]]
httpPath = "/"
handlers = ["hello.Ping"]

Use Vroomy in your application

From your own Go module:

go get github.com/vroomy/vroomy

Keep application plugins in their own files under ./plugins, with each file registering its plugin from init(). Blank-import the package in your main file:

// For an application whose go.mod declares module example.com/myapp:
import _ "example.com/myapp/plugins"

Use your application's module path, not a relative Go import such as "./plugins". The import triggers registration before main runs. Then construct and run the service:

var (
	svc *vroomy.Vroomy
	err error
)

if svc, err = vroomy.New("./config.toml"); err != nil {
	log.Fatal(err)
}

if err = svc.ListenUntilSignal(context.Background()); err != nil {
	log.Fatal(err)
}

This snippet belongs in main with imports for context, log, and github.com/vroomy/vroomy. See the complete example and plugin guide for registration and handlers.

New loads config, changes the process working directory to dir, initializes plugins and dependencies, and registers routes. ListenUntilSignal starts the configured listeners and stops on SIGINT/SIGTERM. Listen itself closes listeners and plugins whenever listening ends, including context cancellation. NewWithConfig accepts an in-memory config but does not apply the file loader's defaults; set Dir explicitly.

Documentation

  • Configuration reference: all fields, defaults, paths, environment accessors, include precedence, routes, and TLS.
  • Plugin guide: registration, lifecycle, handlers, middleware, and dependency injection with complete code examples.
  • Development guide: source map, checks, test coverage, and known implementation gaps.
  • Agent instructions: repository workflow and constraints for coding agents.
  • Go style guide: code organization, declarations, returns, errors, documentation, and tests.

The current runtime does not serve files from a route's target field. Provide a handler instead. Legacy -dataDir / -d flags are not implemented; configure [env].dataDir. These limitations are detailed in the guides above.

Development

go test ./...
go vet ./...
go build ./...

Run gofmt on changed Go files. See the development guide for smoke checks and test isolation. The project license is in LICENCE.

Contributors ✨

Thanks goes to these wonderful people (emoji key):

Josh
Josh

💻 📖
Derek Halman
Derek Halman

💻
Matt Stay
Matt Stay

🎨
BrandenWilliams
BrandenWilliams

💻

This project follows the all-contributors specification. Contributions of any kind welcome!

Documentation

Overview

Package vroomy builds HTTP/HTTPS services from registered Go plugins and TOML configuration. Register plugin instances before calling New or NewWithConfig, then call ListenUntilSignal to run the configured listeners and close the service when listening ends.

Plugins share a process-wide registry. Construction changes the process working directory, calls every plugin's Init, then injects dependencies and calls Load in dependency order. Handlers write responses through apex.Context.

Index

Examples

Constants

View Source
const (
	// ErrProtectedFlag is a legacy sentinel; the current code does not return it.
	ErrProtectedFlag = errors.Error("cannot use protected flag")
	// ErrInvalidHostPolicy is returned when the HostPolicy does not match the intended signature
	ErrInvalidHostPolicy = errors.Error("invalid HostPolicy handler within the autocert plugin")
)
View Source
const (
	// ErrPluginInUse is returned when a service already owns the registry's plugins.
	ErrPluginInUse = errors.Error("registered plugins are already owned by an active service")

	// ErrInvalidTLSDirectory is returned by Listen when TLS is enabled without
	// TLSDir or both AutoCertDir and AutoCertHosts.
	ErrInvalidTLSDirectory = errors.Error("invalid tls directory, cannot be empty when tls port has been set")
	// ErrInvalidPreInitFunc is a legacy sentinel; lifecycle signatures are now
	// enforced by the Plugin interface, and the current code does not return it.
	ErrInvalidPreInitFunc = errors.Error("unsupported header for Init func encountered")
	// ErrInvalidLoadFunc is a legacy sentinel not returned by the current code.
	ErrInvalidLoadFunc = errors.Error("unsupported header for Load func encountered")
	// ErrNotAddressable is returned when a dependency destination cannot be set.
	ErrNotAddressable = errors.Error("provided backend must be addressable")
	// ErrInvalidDir is a legacy sentinel not returned by the current code.
	ErrInvalidDir = errors.Error("invalid directory, cannot be empty")
	// ErrPluginKeyExists identifies duplicate registration keys.
	ErrPluginKeyExists = errors.Error("plugin cannot be added, key already exists")
	// ErrPluginNotLoaded identifies an unregistered plugin key.
	ErrPluginNotLoaded = errors.Error("plugin with that key has not been loaded")
	// ErrExpectedEndParen is returned when an ending parenthesis is missing
	ErrExpectedEndParen = errors.Error("expected ending parenthesis")
	// ErrInvalidPluginHandler identifies nil handlers or invalid handler signatures.
	ErrInvalidPluginHandler = errors.Error("plugin handler not valid")
)
View Source
const (
	// ErrGroupNotFound is returned when a group cannot be found by name
	ErrGroupNotFound = errors.Error("group not found")
)

Variables

This section is empty.

Functions

func Register added in v0.11.0

func Register(key string, pi Plugin) error

Register adds a plugin to the process-wide registry under a unique key. Register non-nil pointers to structs before constructing a service.

Types

type BasePlugin added in v0.11.0

type BasePlugin struct{}

BasePlugin supplies no-op lifecycle methods and a nil backend for embedding.

func (*BasePlugin) Backend added in v0.11.0

func (b *BasePlugin) Backend() any

Backend returns nil. Override it when another plugin needs this plugin's backend.

func (*BasePlugin) Close added in v0.11.0

func (b *BasePlugin) Close() error

Close performs no cleanup.

func (*BasePlugin) Init added in v0.11.0

func (b *BasePlugin) Init(env Environment) error

Init performs no initialization.

func (*BasePlugin) Load added in v0.11.0

func (b *BasePlugin) Load(env Environment) error

Load performs no dependency-dependent setup.

type Config added in v0.15.0

type Config struct {
	Name string `toml:"name"`

	Dir  string `toml:"dir"`
	Port uint16 `toml:"port"`

	// TLSPort to listen on. To use TLS one of the two must be set:
	//	- TLSDir
	//	- AutoCertHosts/AutoCertDir
	TLSPort uint16 `toml:"tlsPort"`

	TLSDir      string `toml:"tlsDir"`
	AllowNonTLS bool   `toml:"allowNonTLS"`

	IncludeConfig

	// Flags is a legacy field with no active runtime consumer.
	Flags map[string]string `toml:"-"`

	// Plugins stores import-path metadata with no active runtime consumer.
	// It is separate from IncludeConfig.Plugins and does not filter the registry.
	Plugins []string `toml:"plugins"`

	// ErrorLogger receives apex request errors; initialization/listen errors
	// are returned to the caller instead.
	ErrorLogger func(error) `toml:"-"`
}

Config configures a Vroomy service. NewWithConfig retains and mutates this value.

func NewConfig added in v0.15.0

func NewConfig(loc string) (cfg *Config, err error)

NewConfig decodes loc and its includes, defaults Dir to "./", and adds process environment entries whose keys are absent from the configured environment. File paths are relative to the current working directory, not loc's directory.

func (*Config) GetFilepath added in v0.19.0

func (c *Config) GetFilepath() (filepath string)

GetFilepath returns config.toml within the CONFIG_PATH process environment directory, or the current directory if CONFIG_PATH is unset. It does not use c.

func (*Config) GetRouteGroup added in v0.15.0

func (c *Config) GetRouteGroup(name string) (g *RouteGroup, err error)

GetRouteGroup returns the first group matching name, or ErrGroupNotFound. An empty name returns nil, nil to select the root group.

type Environment added in v0.13.0

type Environment map[string]string

Environment holds string configuration values shared with plugin lifecycle hooks.

func (Environment) Get added in v0.13.0

func (e Environment) Get(key string) (out string)

Get returns the value for key, or an empty string if key is absent.

Example
val := exampleEnvironment.Get("foo")
fmt.Println("Value of foo is", val)

func (Environment) GetFloat64 added in v0.18.0

func (e Environment) GetFloat64(key string) (out float64, err error)

GetFloat64 parses a float64, returning zero and nil if key is absent.

Example
var (
	val float64
	err error
)

if val, err = exampleEnvironment.GetFloat64("foo"); err != nil {
	// Handle error here
	return
}

fmt.Println("Value of foo is", val)

func (Environment) GetInt added in v0.18.0

func (e Environment) GetInt(key string) (out int, err error)

GetInt parses a decimal int, returning zero and nil if key is absent.

Example
var (
	val int
	err error
)

if val, err = exampleEnvironment.GetInt("foo"); err != nil {
	// Handle error here
	return
}

fmt.Println("Value of foo is", val)

func (Environment) GetInt64 added in v0.18.0

func (e Environment) GetInt64(key string) (out int64, err error)

GetInt64 parses a decimal int64, returning zero and nil if key is absent.

Example
var (
	val int64
	err error
)

if val, err = exampleEnvironment.GetInt64("foo"); err != nil {
	// Handle error here
	return
}

fmt.Println("Value of foo is", val)

func (Environment) GetTime added in v0.18.0

func (e Environment) GetTime(key, layout string) (out time.Time, err error)

GetTime parses a time using layout, returning the zero time and nil if key is absent.

Example
var (
	val time.Time
	err error
)

if val, err = exampleEnvironment.GetTime("foo", "2006-01-02"); err != nil {
	// Handle error here
	return
}

fmt.Println("Value of foo is", val)

func (Environment) GetTimeInLocation added in v0.18.0

func (e Environment) GetTimeInLocation(key, layout string, loc *time.Location) (out time.Time, err error)

GetTimeInLocation parses a time using layout and loc, returning the zero time and nil if key is absent.

Example
var (
	val time.Time
	err error
)

if val, err = exampleEnvironment.GetTimeInLocation("foo", "2006-01-02", time.Local); err != nil {
	// Handle error here
	return
}

fmt.Println("Value of foo is", val)

func (Environment) Must added in v0.13.0

func (e Environment) Must(key string) (out string, err error)

Must returns an error if key is absent. A present empty string is accepted; despite its name, this method does not panic.

Example
var (
	val string
	err error
)

if val, err = exampleEnvironment.Must("foo"); err != nil {
	// Handle error here
	return
}

fmt.Println("Value of foo is", val)

func (Environment) MustFloat64 added in v0.18.0

func (e Environment) MustFloat64(key string) (out float64, err error)

MustFloat64 requires key to be present and parses its value as a float64.

Example
var (
	val float64
	err error
)

if val, err = exampleEnvironment.MustFloat64("foo"); err != nil {
	// Handle error here
	return
}

fmt.Println("Value of foo is", val)

func (Environment) MustInt added in v0.18.0

func (e Environment) MustInt(key string) (out int, err error)

MustInt requires key to be present and parses its value as a decimal int.

Example
var (
	val int
	err error
)

if val, err = exampleEnvironment.MustInt("foo"); err != nil {
	// Handle error here
	return
}

fmt.Println("Value of foo is", val)

func (Environment) MustInt64 added in v0.18.0

func (e Environment) MustInt64(key string) (out int64, err error)

MustInt64 requires key to be present and parses its value as a decimal int64.

Example
var (
	val int64
	err error
)

if val, err = exampleEnvironment.MustInt64("foo"); err != nil {
	// Handle error here
	return
}

fmt.Println("Value of foo is", val)

func (Environment) MustTime added in v0.18.0

func (e Environment) MustTime(key, layout string) (out time.Time, err error)

MustTime requires key to be present and parses its value using layout.

Example
var (
	val time.Time
	err error
)

if val, err = exampleEnvironment.MustTime("foo", "2006-01-02"); err != nil {
	// Handle error here
	return
}

fmt.Println("Value of foo is", val)

func (Environment) MustTimeInLocation added in v0.18.0

func (e Environment) MustTimeInLocation(key, layout string, loc *time.Location) (out time.Time, err error)

MustTimeInLocation requires key to be present and parses its value using layout and loc.

Example
var (
	val time.Time
	err error
)

if val, err = exampleEnvironment.MustTimeInLocation("foo", "2006-01-02", time.Local); err != nil {
	// Handle error here
	return
}

fmt.Println("Value of foo is", val)

type Flag added in v0.15.0

type Flag struct {
	Name         string `toml:"name"`
	DefaultValue string `toml:"defaultValue"`
	Usage        string `toml:"usage"`
}

Flag represents a legacy TOML flag declaration. The current runtime does not install or apply these declarations.

type IncludeConfig added in v0.15.0

type IncludeConfig struct {
	AutoCertHosts []string `toml:"autoCertHosts"`
	AutoCertDir   string   `toml:"autoCertDir"`

	// Environment supplies string values to every plugin's Init and Load hooks.
	Environment map[string]string `toml:"env"`

	// Include lists paths to load. Entries merged from included files are appended
	// but are not traversed by the current loadIncludes pass.
	Include []string `toml:"include"`

	// Plugins stores included plugin entries; it does not populate the outer
	// Config.Plugins field or limit which registered plugins run.
	Plugins []string `toml:"plugins"`

	// FlagEntries stores legacy flag declarations; no flag parser consumes them.
	FlagEntries []*Flag `toml:"flag"`

	// Groups are the route groups
	Groups []*RouteGroup `toml:"group"`
	// Routes are the routes to listen for and serve
	Routes []*Route `toml:"route"`
}

IncludeConfig contains the configuration fields accepted in included TOML files.

type Plugin added in v0.11.0

type Plugin interface {
	// Init runs before all dependency injection; providers initialize before consumers.
	Init(env Environment) error
	// Load runs after dependencies have been assigned and their plugins loaded.
	Load(env Environment) error
	// Backend returns the value injected into consumers' tagged fields.
	Backend() any
	// Close releases resources after partial or successful Init, in reverse dependency order.
	Close() error
}

Plugin provides lifecycle hooks and an optional shared backend. Register a non-nil pointer to a struct before constructing the service.

type Plugins added in v0.11.0

type Plugins struct {
	// contains filtered or unexported fields
}

Plugins manages a plugin registry. Services use the package-level registry via Register; the zero value is not ready for registration.

func (*Plugins) Close added in v0.11.0

func (p *Plugins) Close() (err error)

Close closes registered plugins in unspecified order and marks the registry closed.

func (*Plugins) Get added in v0.11.0

func (p *Plugins) Get(key string) (pi Plugin, err error)

Get returns a plugin by its registration key.

func (*Plugins) Loaded added in v0.11.0

func (p *Plugins) Loaded() (pm map[string]Plugin)

Loaded returns a copy of the registry map, sharing the same plugin instances.

func (*Plugins) Register added in v0.11.0

func (p *Plugins) Register(key string, pi Plugin) (err error)

Register records a plugin under a unique key without initializing it.

func (*Plugins) Test added in v0.11.0

func (p *Plugins) Test() (err error)

Test is unimplemented and always returns an error. Use go test for repository tests.

func (*Plugins) TestAsync added in v0.11.0

func (p *Plugins) TestAsync(q *queue.Queue) (err error)

TestAsync is unimplemented and always returns an error; q is not used.

type Response added in v0.15.0

type Response struct {
	StatusCode  int
	ContentType string
	Value       any

	// Legacy adoption and callback metadata.
	Adopted  bool
	Callback string
}

Response holds legacy response metadata. The current plugin handler resolver does not consume it; handlers write through apex.Context instead.

func NewAdopedtResponse added in v0.15.0

func NewAdopedtResponse() *Response

NewAdopedtResponse returns a Response with Adopted set to true. The exported name retains its historical spelling.

func NewResponse added in v0.15.0

func NewResponse(statusCode int, contentType string, value any) *Response

NewResponse will return a new Response

type Route added in v0.15.0

type Route struct {
	// HTTPHandlers are Go-supplied handlers; resolved Handlers are appended to them.
	HTTPHandlers []apex.Handler `toml:"-"`

	// Name describes the route.
	Name string `toml:"name"`
	// Group names the parent group; an empty value selects the root.
	Group string `toml:"group"`
	// Method selects PUT, POST, DELETE, or OPTIONS case-insensitively; other values use GET.
	Method string `toml:"method"`
	// HTTPPath is the route path, joined to a nonempty group prefix.
	HTTPPath string `toml:"httpPath"`
	// Target is a legacy file/directory field with no current serving implementation.
	Target string `toml:"target"`
	// Handlers lists registered plugin method references in execution order.
	Handlers []string `toml:"handlers"`
}

Route represents a listening route

func (*Route) String added in v0.15.0

func (r *Route) String() string

String will return a formatted version of the route

type RouteGroup added in v0.15.0

type RouteGroup struct {
	Name string `toml:"name"`
	// Group names the parent group; an empty value selects the root.
	Group string `toml:"group"`
	// Method is decoded but does not restrict the group's routes.
	Method string `toml:"method"`
	// HTTPPath is the group's path prefix.
	HTTPPath string `toml:"httpPath"`
	// Handlers lists plugin method references inherited by descendant routes/groups.
	Handlers []string `toml:"handlers"`

	// HTTPHandlers are Go-supplied handlers; resolved Handlers are appended to them.
	HTTPHandlers []apex.Handler `toml:"-"`

	// G is populated during group initialization.
	G apex.Group `toml:"-"`
}

RouteGroup represents a route group

type Vroomy added in v0.9.0

type Vroomy struct {
	// contains filtered or unexported fields
}

Vroomy manages a web service with exclusive ownership of registered plugins. Construction mutates its config and the process working directory. Plugins supply their own request concurrency guarantees; Close reverses dependency order.

func New

func New(configLocation string) (sp *Vroomy, err error)

New loads a configuration file, defaults a missing dataDir environment key to "data", and constructs the service with NewWithConfig. It does not start listeners.

func NewWithConfig added in v0.9.0

func NewWithConfig(cfg *Config) (vp *Vroomy, err error)

NewWithConfig changes the process working directory to cfg.Dir, exclusively acquires registered plugins, initializes them, and registers routes. It retains and mutates cfg without loading includes or supplying defaults. On failure it closes every plugin whose Init was attempted and restores the working directory. A second service using the registry returns ErrPluginInUse until Close completes.

func (*Vroomy) Close added in v0.9.0

func (v *Vroomy) Close() (err error)

Close closes listeners and plugins in reverse dependency order, then releases the registry for reuse. Repeated calls return errors.ErrIsClosed. Plugins must tolerate Close after a partially failed Init and support Init again for reuse.

func (*Vroomy) Listen added in v0.9.0

func (v *Vroomy) Listen(ctx context.Context) (err error)

Listen runs configured listeners until ctx ends, a listener fails, or Close is called. Every exit closes listeners and plugins and joins listener goroutines. Cancellation preserves ctx.Err(). A service can only listen once.

func (*Vroomy) ListenUntilSignal added in v0.17.5

func (v *Vroomy) ListenUntilSignal(ctx context.Context) error

ListenUntilSignal stops on SIGINT, SIGTERM, or SIGABRT and releases signal notification when listening ends. Context cancellation is normal shutdown; other listener and cleanup errors are preserved.

func (*Vroomy) Port added in v0.9.0

func (v *Vroomy) Port() uint16

Port will return the current HTTP port

func (*Vroomy) TLSPort added in v0.9.0

func (v *Vroomy) TLSPort() uint16

TLSPort will return the current HTTPS port

Directories

Path Synopsis
examples
hello command
Command hello serves the routes in config.example.toml using a local plugin.
Command hello serves the routes in config.example.toml using a local plugin.
hello/plugins
Package plugins registers the hello application's plugins when imported.
Package plugins registers the hello application's plugins when imported.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL