frame

package module
v1.76.3 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2026 License: Apache-2.0 Imports: 48 Imported by: 29

README

Frame

Build Status Ask DeepWiki

A fast, extensible Golang framework with a clean plugin-based architecture.

Frame helps you spin up HTTP and gRPC services with minimal boilerplate while keeping strong runtime management, observability, and portable infrastructure via Go Cloud.

Features

  • HTTP and gRPC servers with built-in lifecycle management
  • Datastore setup using GORM with migrations and multi-tenancy
  • Queue publish/subscribe (Go Cloud drivers: mem://, nats://, etc.)
  • Cache manager with multiple backends
  • OpenTelemetry tracing, metrics, and logs
  • OAuth2/JWT authentication and authorization adapters
  • Worker pool for background tasks
  • Localization utilities

Install

go get -u github.com/pitabwire/frame

Minimal Example

package main

import (
    "context"
    "net/http"

    "github.com/pitabwire/frame"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Frame says hello"))
    })

    _, svc := frame.NewService(
        frame.WithName("hello"),
        frame.WithHTTPHandler(http.DefaultServeMux),
    )

    _ = svc.Run(context.Background(), ":8080")
}

Documentation

Docs Site (MkDocs)

pip install mkdocs mkdocs-material
mkdocs serve

Development

To run tests, start the Docker Compose file in ./tests, then run:

go test -json -cover ./...

Contributing

If Frame helped you, please consider starring the repo and sharing it.

We’re actively looking for contributions that make Frame easier to use and more productive for Go teams. Examples:

  • Improve onboarding guides or add real-world examples
  • Add new Go Cloud drivers (queue, cache, datastore)
  • Add middleware, interceptors, or CLI tooling
  • Expand testing utilities or reference architectures

AI-assisted contributions are welcome. If you use AI tools, please verify behavior locally and include tests where relevant.

Open an issue or PR with your idea — even small improvements make a big difference.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrHealthCheckFailed = errors.New("health check failed")
View Source
var ErrTLSPathsNotProvided = errors.New("TLS certificate path or key path not provided")

Functions

func ErrorIsNotFound added in v1.67.11

func ErrorIsNotFound(err error) bool

ErrorIsNotFound checks if an error represents a "not found" condition. It handles multiple error types: - Database errors: gorm.ErrRecordNotFound, sql.ErrNoRows (via ErrorIsNoRows) - gRPC errors: codes.NotFound - Generic errors: error messages containing "not found" (case-insensitive).

func NewGrpcHealthServer added in v1.13.3

func NewGrpcHealthServer(service *Service) grpc_health_v1.HealthServer

func SubmitJob added in v1.28.0

func SubmitJob[T any](ctx context.Context, s *Service, job workerpool.Job[T]) error

SubmitJob used to submit jobs to our worker pool for processing. Once a job is submitted the end user does not need to do any further tasks One can ideally also wait for the results of their processing for their specific job by listening to the job's ResultChan.

func ToContext

func ToContext(ctx context.Context, service *Service) context.Context

ToContext pushes a service instance into the supplied context for easier propagation.

Types

type Checker added in v1.7.13

type Checker interface {
	CheckHealth() error
}

Checker wraps the CheckHealth method.

CheckHealth returns nil if the resource is healthy, or a non-nil error if the resource is not healthy. CheckHealth must be safe to call from multiple goroutines.

type CheckerFunc added in v1.7.13

type CheckerFunc func() error

CheckerFunc is an adapter type to allow the use of ordinary functions as health checks. If f is a function with the appropriate signature, CheckerFunc(f) is a Checker that calls f.

func (CheckerFunc) CheckHealth added in v1.7.13

func (f CheckerFunc) CheckHealth() error

CheckHealth calls f().

type Option

type Option func(ctx context.Context, service *Service)

func WithBackgroundConsumer added in v1.43.0

func WithBackgroundConsumer(deque func(_ context.Context) error) Option

WithBackgroundConsumer sets a background consumer function for the worker pool.

func WithCache added in v1.62.0

func WithCache(name string, rawCache cache.RawCache) Option

WithCache adds a raw cache with the given name to the service.

func WithCacheManager added in v1.62.0

func WithCacheManager() Option

WithCacheManager adds a cache manager to the service.

func WithConfig added in v1.42.0

func WithConfig(cfg any) Option

WithConfig Option that helps to specify or override the configuration object of our service.

func WithDatastore added in v1.42.0

func WithDatastore(opts ...pool.Option) Option

func WithDatastoreConnection added in v1.42.0

func WithDatastoreConnection(postgresqlConnection string, readOnly bool) Option

WithDatastoreConnection Option method to store a connection that will be utilized when connecting to the database.

func WithDatastoreConnectionWithName added in v1.42.0

func WithDatastoreConnectionWithName(
	name string,
	postgresqlConnection string,
	readOnly bool,
	opts ...pool.Option,
) Option

func WithDatastoreConnectionWithOptions added in v1.63.0

func WithDatastoreConnectionWithOptions(name string, opts ...pool.Option) Option

func WithDatastoreManager added in v1.63.0

func WithDatastoreManager() Option

WithDatastoreManager creates and initializes a datastore manager with the given options. This is the low-level function that should rarely be called directly - use WithDatastore instead.

func WithDebugEndpoints added in v1.74.1

func WithDebugEndpoints() Option

WithDebugEndpoints enables AI-friendly introspection endpoints.

func WithDebugEndpointsAt added in v1.74.1

func WithDebugEndpointsAt(basePath string) Option

WithDebugEndpointsAt enables introspection endpoints at a custom base path.

func WithDriver added in v1.56.1

func WithDriver(driver ServerDriver) Option

WithDriver setsup a driver, mostly useful when writing tests against the frame service.

func WithEnableGRPCServerReflection added in v1.43.0

func WithEnableGRPCServerReflection() Option

WithEnableGRPCServerReflection enables gRPC server reflection.

func WithEnvironment added in v1.55.0

func WithEnvironment(environment string) Option

WithEnvironment specifies the environment the service will utilize.

func WithGRPCPort added in v1.43.0

func WithGRPCPort(port string) Option

WithGRPCPort specifies the gRPC port for the server to bind to.

func WithGRPCServer added in v1.43.0

func WithGRPCServer(grpcServer *grpc.Server) Option

WithGRPCServer specifies an instantiated gRPC server with an implementation that can be utilized to handle incoming requests.

func WithGRPCServerListener added in v1.43.0

func WithGRPCServerListener(listener net.Listener) Option

WithGRPCServerListener specifies a user-preferred gRPC listener instead of the default provided one.

func WithHTTPClient added in v1.59.1

func WithHTTPClient(opts ...client.HTTPOption) Option

WithHTTPClient configures the HTTP client used by the service. This allows customizing the HTTP client's behavior such as timeout, transport, etc.

func WithHTTPHandler added in v1.43.0

func WithHTTPHandler(h http.Handler) Option

WithHTTPHandler specifies an HTTP handlers that can be used to handle inbound HTTP requests.

func WithHTTPMiddleware added in v1.73.0

func WithHTTPMiddleware(middleware ...func(http.Handler) http.Handler) Option

WithHTTPMiddleware registers one or more HTTP middlewares. Middlewares wrap the application handler in the order supplied.

func WithHealthCheckPath added in v1.42.0

func WithHealthCheckPath(path string) Option

WithHealthCheckPath Option checks that the system is up and running.

func WithInMemoryCache added in v1.62.0

func WithInMemoryCache(name string) Option

WithInMemoryCache adds an in-memory cache with the given name.

func WithLogger added in v1.38.0

func WithLogger(opts ...util.Option) Option

WithLogger Option that helps with initialization of our internal dbLogger.

func WithName added in v1.55.0

func WithName(name string) Option

WithName specifies the name the service will utilize.

func WithOpenAPIBasePath added in v1.74.0

func WithOpenAPIBasePath(path string) Option

WithOpenAPIBasePath sets the base path used to serve OpenAPI specs. The default is /debug/frame/openapi.

func WithOpenAPISpec added in v1.74.0

func WithOpenAPISpec(name, filename string, content []byte) Option

WithOpenAPISpec registers a single OpenAPI spec with the service. Content should be provided from compile-time embedded assets.

func WithOpenAPISpecsFromFS added in v1.74.0

func WithOpenAPISpecsFromFS(f fs.FS, dir string) Option

WithOpenAPISpecsFromFS registers all .json OpenAPI specs from an embedded FS directory. Use //go:embed to provide the fs.FS at compile time.

func WithPlugin added in v1.74.1

func WithPlugin(name string, opt Option) Option

WithPlugin wraps an option and registers its name for introspection.

func WithRegisterEvents added in v1.42.0

func WithRegisterEvents(evt ...events.EventI) Option

WithRegisterEvents registers events for the service. All events are unique and shouldn't share a name otherwise the last one registered will take precedence.

func WithRegisterPublisher added in v1.42.0

func WithRegisterPublisher(reference string, queueURL string) Option

WithRegisterPublisher Option to register publishing path referenced within the system.

func WithRegisterServerOauth2Client added in v1.62.1

func WithRegisterServerOauth2Client() Option

func WithRegisterSubscriber added in v1.42.0

func WithRegisterSubscriber(reference string, queueURL string,
	handlers ...queue.SubscribeWorker) Option

WithRegisterSubscriber Option to register a new subscription handlers.

func WithTelemetry added in v1.63.0

func WithTelemetry(opts ...telemetry.Option) Option

WithTelemetry adds required telemetry config options to the service.

func WithTranslation added in v1.62.0

func WithTranslation(translationsFolder string, languages ...string) Option

WithTranslation Option that helps to specify or override the configuration object of our service.

func WithVersion added in v1.55.0

func WithVersion(version string) Option

WithVersion specifies the version the service will utilize.

func WithWorkerPoolOptions added in v1.43.0

func WithWorkerPoolOptions(options ...workerpool.Option) Option

WithWorkerPoolOptions provides a way to set custom options for the ants worker pool. Renamed from WithAntsOptions and changed parameter type.

type RouteInfo added in v1.74.1

type RouteInfo struct {
	Method  string `json:"method"`
	Path    string `json:"path"`
	Handler string `json:"handler"`
}

type RouteLister added in v1.74.1

type RouteLister interface {
	Routes() []RouteInfo
}

type RouteRegistry added in v1.74.1

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

RouteRegistry wraps http.ServeMux and records registered routes for introspection.

func NewRouteRegistry added in v1.74.1

func NewRouteRegistry() *RouteRegistry

func (*RouteRegistry) Handle added in v1.74.1

func (r *RouteRegistry) Handle(pattern string, handler http.Handler)

func (*RouteRegistry) HandleFunc added in v1.74.1

func (r *RouteRegistry) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))

func (*RouteRegistry) HandleRoute added in v1.74.1

func (r *RouteRegistry) HandleRoute(method, pattern, name string, handler func(http.ResponseWriter, *http.Request))

HandleRoute records method-aware routes for introspection.

func (*RouteRegistry) Routes added in v1.74.1

func (r *RouteRegistry) Routes() []RouteInfo

func (*RouteRegistry) ServeHTTP added in v1.74.1

func (r *RouteRegistry) ServeHTTP(w http.ResponseWriter, req *http.Request)

type ServerDriver added in v1.56.0

type ServerDriver interface {
	driver.Server
	driver.TLSServer
}

type Service

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

Service framework struct to hold together all application components An instance of this type scoped to stay for the lifetime of the application. It is pushed and pulled from contexts to make it easy to pass around.

func FromContext

func FromContext(ctx context.Context) *Service

func NewService

func NewService(opts ...Option) (context.Context, *Service)

NewService creates a new instance of Service with the name and supplied options. Internally it calls NewServiceWithContext and creates a background context for use.

func NewServiceWithContext added in v1.25.3

func NewServiceWithContext(ctx context.Context, opts ...Option) (context.Context, *Service)

NewServiceWithContext creates a new instance of Service with context, name and supplied options It is used together with the Init option to setup components of a service that is not yet running.

func (*Service) AddCleanupMethod

func (s *Service) AddCleanupMethod(f func(ctx context.Context))

AddCleanupMethod Adds user defined functions to be run just before completely stopping the service. These are responsible for properly and gracefully stopping active components.

func (*Service) AddHealthCheck

func (s *Service) AddHealthCheck(checker Checker)

AddHealthCheck Adds health checks that are run periodically to ascertain the system is ok The arguments are implementations of the checker interface and should work with just about any system that is given to them.

func (*Service) AddPreStartMethod added in v1.1.3

func (s *Service) AddPreStartMethod(f func(ctx context.Context, s *Service))

AddPreStartMethod Adds user defined functions that can be run just before the service starts receiving requests but is fully initialized.

func (*Service) AddPublisherStartup added in v1.62.0

func (s *Service) AddPublisherStartup(f func(ctx context.Context, s *Service))

AddPublisherStartup Adds publisher initialization functions that run before subscribers.

func (*Service) AddStartupError added in v1.62.0

func (s *Service) AddStartupError(err error)

AddStartupError stores errors that occur during startup initialization.

func (*Service) AddSubscriberStartup added in v1.62.0

func (s *Service) AddSubscriberStartup(f func(ctx context.Context, s *Service))

AddSubscriberStartup Adds subscriber initialization functions that run after publishers.

func (*Service) CacheManager added in v1.62.0

func (s *Service) CacheManager() cache.Manager

CacheManager returns the service's cache manager.

func (*Service) Config added in v1.7.13

func (s *Service) Config() any

func (*Service) DatastoreManager added in v1.63.0

func (s *Service) DatastoreManager() datastore.Manager

DatastoreManager returns the service's datastore manager.

func (*Service) Environment added in v1.7.13

func (s *Service) Environment() string

Environment gets the runtime environment of the service.

func (*Service) EventsManager added in v1.64.8

func (s *Service) EventsManager() events.Manager

func (*Service) GetRawCache added in v1.62.0

func (s *Service) GetRawCache(name string) (cache.RawCache, bool)

GetRawCache is a convenience method to get a raw cache by name from the service.

func (*Service) GetStartupErrors added in v1.62.0

func (s *Service) GetStartupErrors() []error

GetStartupErrors returns all errors that occurred during startup.

func (*Service) H added in v1.12.5

func (s *Service) H() http.Handler

func (*Service) HTTPClientManager added in v1.63.0

func (s *Service) HTTPClientManager() client.Manager

HTTPClientManager obtains an instrumented http client for making appropriate calls downstream.

func (*Service) HandleHealth added in v1.12.5

func (s *Service) HandleHealth(w http.ResponseWriter, _ *http.Request)

HandleHealth returns 200 if it is healthy, 500 otherwise.

func (*Service) HandleHealthByDefault added in v1.12.6

func (s *Service) HandleHealthByDefault(w http.ResponseWriter, r *http.Request)

HandleHealthByDefault returns 200 if it is healthy, 500 when there is an err or 404 otherwise.

func (*Service) HealthCheckers added in v1.7.13

func (s *Service) HealthCheckers() []Checker

func (*Service) Init added in v1.0.4

func (s *Service) Init(ctx context.Context, opts ...Option)

Init evaluates the options provided as arguments and supplies them to the service object. If called after initial startup, it will execute any new startup methods immediately.

func (*Service) LocalizationManager added in v1.63.0

func (s *Service) LocalizationManager() localization.Manager

func (*Service) Log added in v1.41.0

func (s *Service) Log(ctx context.Context) *util.LogEntry

func (*Service) Name added in v1.4.0

func (s *Service) Name() string

Name gets the name of the service. Its the first argument used when NewService is called.

func (*Service) OpenAPIRegistry added in v1.74.0

func (s *Service) OpenAPIRegistry() *openapi.Registry

func (*Service) QueueManager added in v1.63.0

func (s *Service) QueueManager() queue.Manager

func (*Service) Run

func (s *Service) Run(ctx context.Context, address string) error

Run keeps the service useful by handling incoming requests.

func (*Service) SLog added in v1.38.0

func (s *Service) SLog(ctx context.Context) *slog.Logger

func (*Service) SecurityManager added in v1.63.0

func (s *Service) SecurityManager() security.Manager

func (*Service) Stop

func (s *Service) Stop(ctx context.Context)

Stop Used to gracefully run clean up methods ensuring all requests that were being handled are completed well without interuptions.

func (*Service) TLSEnabled added in v1.13.0

func (s *Service) TLSEnabled() bool

func (*Service) TelemetryManager added in v1.66.0

func (s *Service) TelemetryManager() telemetry.Manager

func (*Service) Version added in v1.7.13

func (s *Service) Version() string

Version gets the release version of the service.

func (*Service) WorkManager added in v1.62.0

func (s *Service) WorkManager() workerpool.Manager

Directories

Path Synopsis
cmd
frame command
examples
datastore-basic command
grpc-basic command
http-basic command
queue-basic command
authorizer
Package authorizer provides an Ory Keto adapter implementation for the security.Authorizer interface.
Package authorizer provides an Ory Keto adapter implementation for the security.Authorizer interface.
tools

Jump to

Keyboard shortcuts

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