frame

package module
v1.69.13 Latest Latest
Warning

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

Go to latest
Published: Dec 27, 2025 License: Apache-2.0 Imports: 42 Imported by: 29

README

frame Build Status Ask DeepWiki

A simple frame for quickly setting up api servers based on gocloud framework.

Features include:

  • An http server
  • A grpc server
  • Database setup using Gorm with migrations and multitenancy support
  • Easy queue publish and subscription support
  • Localization
  • Authentication adaptor for oauth2 and jwt access
  • Authorization adaptor

The goal of this project is to simplify starting up servers with minimal boiler plate code. All components are very pluggable with only the necessary configured items loading at runtime thanks to the power of go-cloud under the hood.

Getting started:

    go get -u github.com/pitabwire/frame

Example

import (
	"context"
	"fmt"
	"github.com/gorilla/mux"
	"github.com/pitabwire/frame"
	"log"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Frame says yelloo!")
}


func main() {

	serviceName := "service_authentication"
	ctx := context.Background()

	router := mux.NewRouter().StrictSlash(true)
	router.HandleFunc("/", handler)

	server := frame.HttpHandler(router)
	service := frame.NewService(frame.WithName(serviceName,server))
	err := service.Run(ctx, ":7654")
	if err != nil {
		log.Fatal("main -- Could not run Server : %v", err)
	}

}

Detailed guides can be found here

development

To run tests start the docker compose file in ./tests then run :

    go test -json -cover ./...

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 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 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 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 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

FromContext obtains a service instance being propagated through the context.

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) 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

Jump to

Keyboard shortcuts

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