Skip to content
/ digi Public

zphia/digi

Repository files navigation

Digi

A small personal library I use to kickstart the creation of personal projects with a few minimum niceties.

Features

Project Organization

The Server and Runnable types provide a framework for organizing growing projects. A typical project structure would look like this:

|- cmd
|   `- server
|       `- main.go
|- processes
|   `- example
|       |- handlers
|       |   |- some_handler.go
|       |   `- some_handler_test.go
|       `- example.go
|- go.mod
`- go.sum

Example

This is a one-file example of using the Server and Runnable types.

package main

import (
	"net/http"

	"github.com/zphia/digi"
	"github.com/labstack/echo/v4"
)

type example struct{}

func (e *example) Name() string {
    return "example"
}

func (e *example) Start(logger digi.Logger, i *digi.Injector) error {
	logger.Info("Inside the example!")

	web, err := digi.InjectorGet[*echo.Echo](i)
	if err != nil {
		return err
	}

	web.GET("/example", func(c echo.Context) error {
		return c.String(http.StatusOK, "Inside the handler!")
	})

	return nil
}

func (e *example) Stop() error {
	return nil
}

func main() {
	digi.NewServer().Start(&example{}).Wait()
}

Dependency Management

The digi.Injector type provide a simple dependency injection solution.

Dependencies can be registered in any order and are initialized and cached lazily. In the below example even though the after depedency doesn't exist when the first dependency is registered, the first dependency can still retrieve the value:

i := digi.NewInjector()

digi.InjectorSet[int](i, func(i *digi.Injector) (*digi.Dependency[int], error) {
    after, err := digi.InjectorGetNamed[int](i, "after")
    if err != nil {
        return nil, err
    }

    return &digi.Dependency[int]{
        Value: 7 + first,
    }, err
})

digi.InjectorSetNamed[int](i, "after", func(i *digi.Injector) (*digi.Dependency[int], error) {
    return &digi.Dependency[int]{
        Value: 5,
	}, nil
})

value, _ := digi.InjectorGet[int](i)

Mocking Time

Use the digi.Clock type to retrieve the current time and allow for testing of code that relies on the current time.

The dependency injector will have an instance of digi.Clock provided by default from the digi.SystemClock type.

Environment Variables

The provided environment variables are parsed by default:

HTTP_PORT

The default HTTP port for the server to listen to.

Defaults to 0 which will randomize the port.

LOG_JSON

Whether the logger defaults to JSON output.

Defaults to false.

LOG_LEVEL

The default log level to output.

Defaults to DEBUG.

Valid values are:

  • DEBUG
  • INFO
  • WARNING
  • ERROR
  • FATAL

VERSION

Version of the application.

No default.

About

A personal framework to kickstart the creation of services big and small.

Resources

Stars

Watchers

Forks

Contributors