helix

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 29 Imported by: 0

README

Helix

CI Coverage Go Report Card

Helix est un framework backend Go inspire de Spring Boot, concu pour creer des APIs avec moins de boilerplate tout en restant idiomatique. Il combine injection de dependances, HTTP declaratif, repository generique, configuration centralisee, observabilite, securite, scheduling et CLI de developpement.

Sommaire

Installation

Prerequis

  • Go 1.21 ou plus recent
  • Un module Go applicatif
go version
go mod init example.com/helix-users
go get github.com/enokdev/helix

Helix est publie comme module Go. go get github.com/enokdev/helix ajoute le framework a votre go.mod et telecharge les dependances necessaires.

Quick Start

Creer votre premiere application Helix
mkdir helix-users && cd helix-users
go mod init example.com/helix-users
go get github.com/enokdev/helix

Helix structure un service backend en trois types de composants :

type UserRepository struct{ helix.Repository }
type UserService struct {
    helix.Service
    Repo *UserRepository `inject:"true"`
}
type UserController struct {
    helix.Controller
    Service *UserService `inject:"true"`
}

func (c *UserController) Index() []User { return c.Service.Repo.FindAll() }

Mode zero-config : si Fiber est dans votre go.mod et que vous avez un config/application.yaml, un simple helix.Run() suffit — le framework detecte les starters, câble les composants et gere le lifecycle HTTP.

func main() {
    if err := helix.Run(); err != nil {
        log.Fatal(err)
    }
}

Mode explicite : fournissez vos composants via helix.App{Components: ...} pour un contrôle total.

func main() {
    if err := helix.Run(helix.App{
        Components: []any{
            NewUserRepository(),
            &UserService{},
            &UserController{},
        },
    }); err != nil {
        log.Fatal(err)
    }
}

helix.Run gere le cycle de vie complet : demarrage, ecoute de SIGTERM/SIGINT et arret propre. Consultez examples/crud-api pour un exemple complet ou examples/zero-config pour le mode zero-config.

Explorer l'exemple complet

Une API CRUD users en memoire est disponible dans ce depot :

git clone https://github.com/enokdev/helix.git
cd helix
go run ./examples/crud-api

Dans un autre terminal :

curl http://localhost:8080/users
curl -X POST http://localhost:8080/users \
  -H 'Content-Type: application/json' \
  -d '{"name":"Ada Lovelace","email":"ada@example.com"}'
curl http://localhost:8080/users/1
curl -X PUT http://localhost:8080/users/1 \
  -H 'Content-Type: application/json' \
  -d '{"name":"Ada Byron","email":"ada.byron@example.com"}'
curl -X DELETE http://localhost:8080/users/1

Fonctionnalites

  • Injection de dependances via helix.Service, helix.Controller, helix.Repository et helix.Component.
  • Bootstrap zero-config via helix.Run() : starters detectes automatiquement (web, security, scheduling) selon les marqueurs de composants et go.mod.
  • Bootstrap explicite via helix.Run(helix.App{Components: ...}) pour un controle total.
  • Resolution DI par reflection par defaut, avec mode wire pour le codegen compile-time.
  • Routing HTTP par conventions Index, Show, Create, Update, Delete et directives //helix:route.
  • Binding type des query params et body JSON, validation automatique et mapping retour vers status HTTP.
  • Repository generique data.Repository[T, ID, TX] et adaptateur GORM via data/gorm.NewRepository.
  • Tests d'application avec helix.NewTestApp, helix.GetBean[T] et helix.MockBean[T].
  • Configuration YAML, profils et variables d'environnement avec priorite ENV > profile > application.yaml > default.
  • Endpoints d'observabilite /actuator/health, /actuator/metrics et /actuator/info.
  • Securite JWT/RBAC, guards declaratifs, scheduling cron et CLI helix.

Exemples

  • API CRUD users : service, repository en memoire, controller declaratif et lifecycle HTTP geré par le starter web.
  • API securisee JWT/RBAC : authentification JWT, guards RBAC declaratifs et configuration globale de securite.
  • Zero-config : helix.Run() sans argument — le framework detecte et configure tout automatiquement.

Commandes utiles :

go run ./examples/crud-api
go run ./examples/secured-api
go run ./examples/zero-config
go test ./...

Guides

Developpement du framework

Pour contribuer a Helix lui-meme :

git clone https://github.com/enokdev/helix.git
cd helix
go mod tidy
go test ./...
go build ./...

Avant d'ouvrir une pull request :

golangci-lint run

Si golangci-lint n'est pas installe localement, lancez au minimum :

go vet ./...

Licence

MIT - voir LICENSE.

Documentation

Overview

Package helix is the root package of the Helix framework - a Go backend framework inspired by Spring Boot.

See core for the DI container, web for HTTP routing, [data] for the repository pattern, and config for configuration loading.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidComponent is returned when a value cannot be registered as a Helix component.
	ErrInvalidComponent = errors.New("helix: invalid component")
	// ErrScanRequiresComponents is returned when source scan finds marker types
	// that cannot be instantiated by the runtime bootstrap.
	ErrScanRequiresComponents = errors.New("helix: scan requires runtime components")
)

Functions

func GetBean

func GetBean[T any](app *TestApp) T

GetBean resolves a component from a Helix test app.

func RegisterWebSetup

func RegisterWebSetup(fn func() error)

RegisterWebSetup stores the bootstrap function emitted by generated web route and handler registrations.

func RegisterWireSetup

func RegisterWireSetup(fn func(*core.Container) error)

RegisterWireSetup stores the bootstrap function emitted by generated wiring.

func Run

func Run(opts ...App) error

Run builds the default reflection-based container, registers application components, starts lifecycle hooks, waits for shutdown, and stops cleanly.

Run accepts an optional App argument. When called with no arguments (or with a zero-value App), the framework bootstraps automatically: it loads configuration from config/application.yaml or application.yaml (absence is not an error), auto-detects which starters to activate, and uses a registered wire setup function when available.

Types

type App

type App struct {
	// Scan lists package or filesystem patterns that should be inspected for
	// Helix component markers. Runtime scan cannot instantiate discovered Go
	// types by itself; provide Components for values that should be registered.
	Scan []string
	// Components contains already-instantiated components to auto-register.
	Components []any
	// Starters lists the auto-configuration modules to activate before
	// registering application components. Evaluated in canonical order.
	Starters []starter.Entry
	// ShutdownTimeout overrides the default lifecycle shutdown budget.
	ShutdownTimeout time.Duration
	// Logger overrides the logger used by lifecycle shutdown.
	Logger *slog.Logger
	// Mode selects the resolver strategy. The zero value keeps reflection mode.
	Mode RunMode
	// contains filtered or unexported fields
}

App describes the application bootstrap configuration used by Run.

type Component

type Component struct{}

Component marks a struct as a generic Helix component.

type ConfigReloadable

type ConfigReloadable = config.Reloadable

ConfigReloadable is implemented by components that react after a successful configuration reload.

type Controller

type Controller struct{}

Controller marks a struct as a Helix controller component.

type ErrorHandler

type ErrorHandler struct{}

ErrorHandler marks a struct as a centralized HTTP error handler component.

type NotFoundError

type NotFoundError struct {
	Message string
}

NotFoundError represents a missing resource returned by application code.

func (NotFoundError) Error

func (e NotFoundError) Error() string

Error implements error.

func (NotFoundError) ErrorCode

func (e NotFoundError) ErrorCode() string

ErrorCode returns the machine-readable error code.

func (NotFoundError) ErrorField

func (e NotFoundError) ErrorField() string

ErrorField returns the field associated with this error, when any.

func (NotFoundError) ErrorType

func (e NotFoundError) ErrorType() string

ErrorType returns the structured error type name.

func (NotFoundError) StatusCode

func (e NotFoundError) StatusCode() int

StatusCode returns the HTTP status associated with this error.

type Repository

type Repository struct{}

Repository marks a struct as a Helix repository component.

type RunMode

type RunMode string

RunMode selects the DI resolver strategy.

const (
	// ModeReflect uses the default reflection-based resolver.
	ModeReflect RunMode = ""
	// ModeWire uses compile-time generated DI wiring.
	ModeWire RunMode = "wire"
)

type SecurityConfigurer

type SecurityConfigurer struct{}

SecurityConfigurer marks a struct as a global security configuration component.

type Service

type Service struct{}

Service marks a struct as a Helix service component.

type TestApp

type TestApp = testutil.App

TestApp is a Helix application container scoped to a Go test.

func NewTestApp

func NewTestApp(t testing.TB, opts ...TestOption) *TestApp

NewTestApp creates, starts, and registers cleanup for a Helix test app.

type TestOption

type TestOption = testutil.Option

TestOption configures a Helix test application.

func MockBean

func MockBean[T any](impl T) TestOption

MockBean replaces components assignable to T with impl in a Helix test app.

func TestComponents

func TestComponents(components ...any) TestOption

TestComponents registers components in the test container before startup.

func TestConfigDefaults

func TestConfigDefaults(values map[string]any) TestOption

TestConfigDefaults configures fallback values for the test config loader.

func TestConfigPaths

func TestConfigPaths(paths ...string) TestOption

TestConfigPaths overrides directories searched for application test config.

func TestContainerOptions

func TestContainerOptions(opts ...core.Option) TestOption

TestContainerOptions appends core container options to the test container.

type ValidationError

type ValidationError struct {
	Message string
	Field   string
}

ValidationError represents invalid user input returned by application code.

func (ValidationError) Error

func (e ValidationError) Error() string

Error implements error.

func (ValidationError) ErrorCode

func (e ValidationError) ErrorCode() string

ErrorCode returns the machine-readable error code.

func (ValidationError) ErrorField

func (e ValidationError) ErrorField() string

ErrorField returns the field associated with this error, when any.

func (ValidationError) ErrorType

func (e ValidationError) ErrorType() string

ErrorType returns the structured error type name.

func (ValidationError) StatusCode

func (e ValidationError) StatusCode() int

StatusCode returns the HTTP status associated with this error.

Directories

Path Synopsis
cli
Package cli provides the Helix project and module generator CLI tool (e.g.
Package cli provides the Helix project and module generator CLI tool (e.g.
cmd
helix command
Package config provides YAML and ENV configuration loading with priority chain ENV > profile YAML > application.yaml > DEFAULT for the Helix framework.
Package config provides YAML and ENV configuration loading with priority chain ENV > profile YAML > application.yaml > DEFAULT for the Helix framework.
Package core provides the dependency injection container and lifecycle management for the Helix framework.
Package core provides the dependency injection container and lifecycle management for the Helix framework.
Package data provides the generic repository pattern and ORM adapter interfaces for the Helix framework.
Package data provides the generic repository pattern and ORM adapter interfaces for the Helix framework.
gorm
Package gorm provides the GORM-based implementation of the Helix repository interfaces.
Package gorm provides the GORM-based implementation of the Helix repository interfaces.
examples
crud-api command
secured-api command
zero-config command
Package main demonstrates the zero-config bootstrap mode of the Helix framework.
Package main demonstrates the zero-config bootstrap mode of the Helix framework.
Package observability provides Prometheus metrics, structured logging via slog, and OpenTelemetry tracing for the Helix framework.
Package observability provides Prometheus metrics, structured logging via slog, and OpenTelemetry tracing for the Helix framework.
Package scheduler provides declarative task scheduling support, backed by a robfig/cron adapter, for the Helix framework.
Package scheduler provides declarative task scheduling support, backed by a robfig/cron adapter, for the Helix framework.
Package security provides JWT authentication, RBAC middleware, and security configuration for the Helix framework.
Package security provides JWT authentication, RBAC middleware, and security configuration for the Helix framework.
Package starter provides auto-configuration modules (web, data, security, observability) for the Helix framework.
Package starter provides auto-configuration modules (web, data, security, observability) for the Helix framework.
internal/starterutil
Package starterutil provides shared helpers for Helix starters.
Package starterutil provides shared helpers for Helix starters.
web
Package testutil provides testing helpers, mock beans, and test application container utilities for the Helix framework.
Package testutil provides testing helpers, mock beans, and test application container utilities for the Helix framework.
web
Package web provides HTTP integration, declarative routing, and middleware support for the Helix framework, built on top of Fiber.
Package web provides HTTP integration, declarative routing, and middleware support for the Helix framework, built on top of Fiber.
internal
Package internal contains internal Fiber adapter implementation details not exposed as part of the public web package API.
Package internal contains internal Fiber adapter implementation details not exposed as part of the public web package API.

Jump to

Keyboard shortcuts

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