Help us shape the future of Go! Take the 2026 Go Developer Survey

bedrock

package module
v0.9.3 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2024 License: MIT Imports: 3 Imported by: 7

README

bedrock

Mentioned in Awesome Go Go Reference Go Report Card Coverage build

bedrock provides a minimal, modular and composable foundation for quickly developing services and more use case specific frameworks in Go.

Core Concepts

type App interface {
	Run(context.Context) error
}

App is a simple abstraction over the execution of your specific application type e.g. HTTP server, gRPC server, etc.

type AppBuilder[T any] interface {
	Build(ctx context.Context, cfg T) (App, error)
}

AppBuilder puts the responsibility of App initialization in your hands!

The generic parameter provided to your AppBuilder is, in fact, your custom configuration type, which means no messing with config parsing and unmarshalling yourself!

package config

type Source interface {
	Apply(Store) error
}

The config.Source is arguably the most powerful abstraction defined in any of the bedrock packages. It abstracts over the entire mechanic of sourcing your application configuration. This simple interface can then be implemented in various ways to support loading configuration from different files (e.g. YAML, JSON, TOML) to remote configuration stores (e.g. etcd).

func Run[T any](ctx context.Context, builder AppBuilder[T], srcs ...config.Source) error

The final piece and most crucial piece bedrock provides is the Run function which handles the orchestration of config parsing, app building and, lastly, app execution by relying on the other core abstractions noted above.

Building services with bedrock

bedrock conveniently comes with a couple of Apps already implemented for you. This can significantly aid in shortening your overall development time, as well as, provide an example for how to implement your own custom App.

For example, the below shows how simple it is to implement a RESTful API leveraging the rest.App.

package main

import (
    "context"
	"encoding/json"
	"net/http"
	"strings"

    "github.com/z5labs/bedrock"
    "github.com/z5labs/bedrock/pkg/config"
    "github.com/z5labs/bedrock/rest"
	"github.com/z5labs/bedrock/rest/endpoint"
)

type echoService struct{}

type EchoRequest struct {
	Msg string `json:"msg"`
}

func (EchoRequest) ContentType() string {
	return "application/json"
}

func (req *EchoRequest) UnmarshalBinary(b []byte) error {
	return json.Unmarshal(b, req)
}

type EchoResponse struct {
	Msg string `json:"msg"`
}

func (EchoResponse) ContentType() string {
	return "application/json"
}

func (resp EchoResponse) MarshalBinary() ([]byte, error) {
	return json.Marshal(resp)
}

func (echoService) Handle(ctx context.Context, req *EchoRequest) (*EchoResponse, error) {
	return &EchoResponse{Msg: req.Msg}, nil
}

type Config struct {
	Title string `config:"title"`
	Version string `config:"version"`

	Http struct {
		Port uint `config:"port"`
	} `config:"http"`
}

// here we're defining our AppBuilder as a simple function
// remember bedrock.Run handles config unmarshalling for us
// so we get to work with our custom config type, Config, directly.
func buildRestApp(ctx context.Context, cfg Config) (bedrock.App, error) {
	app := rest.NewApp(
		rest.ListenOn(cfg.Http.Port),
		rest.Title(cfg.Title),
		rest.Version(cfg.Version),
		rest.Endpoint(
			http.MethodPost,
			"/",
			endpoint.NewOperation(
				echoService{},
			),
		),
	)
	return app, nil
}

// would recommend this being a separate file you could use
// go:embed on or use a config.Source that could fetch it
// from a remote store.
var config = `{
	"title": "My Example API",
	"version": "v0.0.0",
	"http": {
		"port": 8080
	}
}`

func main() {
	builder := bedrock.AppBuilderFunc[Config](buildRestApp)

	// Note: Should actually handle error in your code
	_ = bedrock.Run(
		context.Background(),
		builder,
		config.FromJson(strings.NewReader(config)),
	)
}

There you go, an entire RESTful API in less than 100 lines!

This incredibly simple example can theb easily be extended (aka made more production-ready) by leveraging a middleware approach to the App returned by your AppBuilder. Conventiently, bedrock already has a couple common middlewares defined for your use in package app. Two notable middleware implementations are:

Building custom frameworks with bedrock

One of the guiding principals for bedrock is to be composable. This principal comes from the experience gained from working with custom, tailor made frameworks which over their lifetime within an organization are unable to adapt to changing development and deployment patterns. Eventually, these frameworks are abandoned for new ones or completely rewritten to reflect the current state of the organization.

bedrock defines a small set of types and carefully chooses its opinions to balance composability and functionality, as much as it can. The result is, in fact, a framework that isn't necessarily designed for building services directly, but instead meant for building more custom, use case specific frameworks.

For example, bedrock could be used by your organizations platform engineering or framework team(s) to quickly develop internal frameworks which abstract over all of your organizations requirements e.g. OpenTelemetry, Logging, Authenticated endpoints, etc. Then, due to the high composibility of bedrock, any changes within your organization would then be very easy to adapt to within your internal framework. A more concrete example of how a custom framework could look like can be found in example/custom_framework.

Documentation

Overview

Package bedrock provides a minimal foundation for building more complex frameworks on top of.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run added in v0.6.0

func Run[T any](ctx context.Context, builder AppBuilder[T], srcs ...config.Source) error

Run executes the application. It's responsible for reading the provided config sources, unmarshalling them into the generic config type, using the config and builder to build the users App and, lastly, running the returned App.

Example
package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/z5labs/bedrock/pkg/config"
)

type appFunc func(context.Context) error

func (f appFunc) Run(ctx context.Context) error {
	return f(ctx)
}

func main() {
	r := strings.NewReader(`hello: world`)

	// Define a custom config struct which aligns with your
	// the format of your config.Source(s).
	type MyConfig struct {
		Hello string `config:"hello"`
	}

	// Define a AppBuilder.
	builder := AppBuilderFunc[MyConfig](func(ctx context.Context, cfg MyConfig) (App, error) {
		// Inside your AppBuilder.Build is where you should be initializing
		// all dependencies of your code e.g. backend API clients, DB connections, etc.

		// Lastly, initialize something which implements the bedrock.App interface.
		app := appFunc(func(c context.Context) error {
			fmt.Println("hello,", cfg.Hello)
			return nil
		})

		return app, nil
	})

	err := Run(context.Background(), builder, config.FromYaml(r))
	if err != nil {
		fmt.Println(err)
		return
	}
}
Output:
hello, world

Types

type App

type App interface {
	Run(context.Context) error
}

App represents the entry point for user specific code.

type AppBuildError added in v0.6.0

type AppBuildError struct {
	Cause error
}

AppBuildError

func (AppBuildError) Error added in v0.6.0

func (e AppBuildError) Error() string

Error implements the [builtin.error] interface.

func (AppBuildError) Unwrap added in v0.6.0

func (e AppBuildError) Unwrap() error

Unwrap implements the implicit interface used by errors.Is and errors.As.

type AppBuilder added in v0.6.0

type AppBuilder[T any] interface {
	Build(ctx context.Context, cfg T) (App, error)
}

AppBuilder represents anything which can initialize a Runtime.

type AppBuilderFunc added in v0.6.0

type AppBuilderFunc[T any] func(context.Context, T) (App, error)

AppBuilderFunc is a functional implementation of the AppBuilder interface.

func (AppBuilderFunc[T]) Build added in v0.6.0

func (f AppBuilderFunc[T]) Build(ctx context.Context, cfg T) (App, error)

Build implements the RuntimeBuilder interface.

type AppRunError added in v0.6.0

type AppRunError struct {
	Cause error
}

AppRunError

func (AppRunError) Error added in v0.6.0

func (e AppRunError) Error() string

Error implements the [builtin.error] interface.

func (AppRunError) Unwrap added in v0.6.0

func (e AppRunError) Unwrap() error

Unwrap implements the implicit interface used by errors.Is and errors.As.

type ConfigReadError added in v0.6.0

type ConfigReadError struct {
	Cause error
}

ConfigReadError

func (ConfigReadError) Error added in v0.6.0

func (e ConfigReadError) Error() string

Error implements the [builtin.error] interface.

func (ConfigReadError) Unwrap added in v0.6.0

func (e ConfigReadError) Unwrap() error

Unwrap implements the implicit interface used by errors.Is and errors.As.

type ConfigUnmarshalError added in v0.6.0

type ConfigUnmarshalError struct {
	Cause error
}

ConfigUnmarshalError

func (ConfigUnmarshalError) Error added in v0.6.0

func (e ConfigUnmarshalError) Error() string

Error implements the [builtin.error] interface.

func (ConfigUnmarshalError) Unwrap added in v0.6.0

func (e ConfigUnmarshalError) Unwrap() error

Unwrap implements the implicit interface used by errors.Is and errors.As.

Directories

Path Synopsis
circuit module
example
simple_queue command
simple_rest command
fit module
host module
pkg
app
Package app provides helpers for common bedrock.App implementation patterns.
Package app provides helpers for common bedrock.App implementation patterns.
config
Package config provides very easy to use and extensible configuration management capabilities.
Package config provides very easy to use and extensible configuration management capabilities.
config/key
Package key provides types for strongly typed keys in key value pairs.
Package key provides types for strongly typed keys in key value pairs.
health
Package health defines K8s inspired health metrics.
Package health defines K8s inspired health metrics.
noop
Package noop provides no-op implementations to be used in tests and as defaults.
Package noop provides no-op implementations to be used in tests and as defaults.
ptr
Package ptr provides helpers for working with references of values.
Package ptr provides helpers for working with references of values.
Package queue provides multiple patterns which implements the app.Runtime interface.
Package queue provides multiple patterns which implements the app.Runtime interface.
Package rest provides a bedrock.App implementation for building RESTful applications.
Package rest provides a bedrock.App implementation for building RESTful applications.
endpoint
Package endpoint wraps generic RPC style code into a RESTful HTTP endpoint handler.
Package endpoint wraps generic RPC style code into a RESTful HTTP endpoint handler.
retry module

Jump to

Keyboard shortcuts

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