pfw

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 3 Imported by: 0

README

Palma Framework

Framework Go opinionato in costruzione, ispirato a Symfony e Spring Boot. Focalizzato su backend e API, con dependency injection generata a build time. HTTP è il primo trasporto previsto; il nucleo resta indipendente dal protocollo per consentire future integrazioni, per esempio gRPC.

Prima release in preparazione: v0.1.0, con API in evoluzione e licenza MIT. Include generatore DI, cleanup delle risorse, CLI pfw, configurazione, lifecycle e skeleton API con router stdlib o Echo v5. Il nome usato nel codice è pfw.

Principi

  • Costruttori Go normali, dipendenze esplicite.
  • Wiring generato come codice Go leggibile.
  • Errori del grafo durante la generazione.
  • Nessuna reflection o service locator per la DI a runtime.
  • Nessuna struttura di cartelle o nomenclatura obbligatoria: MVC, architettura esagonale e organizzazione per funzionalità sono scelte dell'applicazione.
  • Libreria HTTP a scelta dell'applicazione: standard library, Echo, Chi, Gin o altro, con integrazioni opzionali previste dall'architettura.

Installazione e primo progetto

Richiede Go 1.26 o successivo. Dopo la pubblicazione del tag v0.1.0:

go install github.com/palma99/palma-framework/cmd/pfw@v0.1.0
pfw version
pfw new -template api -router echo -module example.com/myapi ./myapi
cd myapi
go mod tidy
go tool pfw run -env dev

La CLI installata deve essere nel PATH. Per un'applicazione minimale scegliere -template hello-world; per l'API standard scegliere -router stdlib. Il progetto include la CLI come tool Go e fissa la stessa versione della libreria. pfw.toml salva i percorsi dei package bootstrap e main: generate, inspect e run li usano quando ometti il package. Gli argomenti espliciti prevalgono; vedi configurazione dei percorsi.

Per usare soltanto la libreria in un modulo esistente:

go get github.com/palma99/palma-framework@v0.1.0

Fino alla pubblicazione, usare il checkout locale come descritto sotto. La guida al rilascio include verifiche, packaging e pubblicazione. La licenza MIT copre il codice del framework.

Sviluppo

Per creare un progetto esterno da uno skeleton incluso nella CLI:

go run ./cmd/pfw templates
go run ./cmd/pfw new -template api -module example.com/myapi \
  -env dev -framework-dir . /tmp/palma-api

Sono disponibili hello-world e api (architettura esagonale). Per api, -router stdlib è il default; -router echo genera la variante Echo v5. La guida ai template descrive creazione, dipendenze e avvio.

Richiede Go 1.26 o successivo.

go run ./cmd/pfw generate -env local ./examples/httpapi/internal/bootstrap
go run ./cmd/pfw generate -env local -check ./examples/httpapi/internal/bootstrap
go test ./...
go run ./examples/httpapi/cmd/api

L'esempio espone GET http://localhost:8080/users e usa il wiring generato da registrazioni manuali e discovery annotata. Routing e risposte JSON usano Echo v5; il lifecycle gestisce il server HTTP tramite transport/httpserver.

L'esempio API completo organizza dominio, servizi e adapter per funzionalità e implementa creazione, ricerca ed elenco utenti.

La proposta di architettura separa il nucleo implementato dalle convenzioni e funzionalità ancora da decidere. La guida dell'API DI descrive registrazione, generazione e limiti della prima versione.

Il module path è github.com/palma99/palma-framework; il nome del package è pfw.

L'API usa pfw.Constructors per registrare i costruttori e pfw.Implementation (o il suo alias pfw.Bind) per collegare le interfacce. Con pfw.Discover può anche registrare automaticamente le funzioni annotate //pfw:coconut nei package selezionati, combinandole con le registrazioni manuali. Il binding è esplicito di default. pfw.AutoBind() abilita la selezione di un'implementazione concreta unica nella radice o in un modulo. I moduli ereditano il globale, salvo un proprio AutoBind(true/false); con più candidati occorre un binding esplicito.

I costruttori possono restituire T, (T, error) oppure (T, func() error, error) per le risorse. In quest'ultimo caso il composition root usa pfw.BuildWithCleanup, che restituisce il cleanup da eseguire alla chiusura. L'esempio examples/cleanup mostra questo contratto.

Il lifecycle applicativo coordina avvio, supervisione, arresto con timeout e cleanup finale. L'esempio HTTP usa RunSignals() per gestire SIGINT e SIGTERM.

Il package HTTP offre risposte tipizzate, decoder JSON e mapping degli errori applicativi indipendenti dal router. L'esempio Echo lo usa attraverso un mapper iniettato nel controller.

La configurazione carica environment e file .env in struct Go con default, campi richiesti, parsing tipizzato e validazione. L'esempio HTTP usa il prefisso HTTPAPI_ per indirizzo, timeout e utente iniziale. Le impostazioni possono essere raggruppate in sottostruct tramite envPrefix.

Il logger espone un'interfaccia iniettabile e un'implementazione standard basata su log/slog. Gli skeleton API usano un binding esplicito per permettere all'applicazione di sostituirla con il proprio logger.

pfw inspect mostra provider, provenienza, scope, binding, ordine di costruzione e cleanup senza scrivere file. Supporta output testuale e -json:

go run ./cmd/pfw inspect ./examples/httpapi/internal/bootstrap

La guida inspect descrive il report e l'uso in tooling.

La gestione degli ambienti offre ForEnv, override, binding specifici e wiring generato per un ambiente alla volta:

go run ./cmd/pfw run -env local ./examples/httpapi/cmd/api
go run ./cmd/pfw inspect -env production ./examples/httpapi/internal/bootstrap

Documentation

Overview

Package pfw declares dependency graphs for build-time generation. Put declarations in files guarded by //go:build pfw_inject, then run pfw generate. The generated application uses ordinary constructor calls.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Build

func Build[T any](registrations ...Registration) (T, error)

Build declares the root type for an initializer. Initializer parameters are external inputs. Build is a generation marker, never a runtime DI container.

func BuildWithCleanup

func BuildWithCleanup[T any](registrations ...Registration) (T, func() error, error)

BuildWithCleanup declares a root whose resources are owned by the initializer. On success the generated function returns a cleanup that runs once, in reverse construction order. On failure cleanup runs automatically and is returned nil. Existing constructors returning T or (T, error) are supported as well.

Types

type Environment

type Environment string

Environment is an application-defined name, validated without predefined semantics.

const (
	Local      Environment = "local"
	Staging    Environment = "staging"
	Production Environment = "production"
)

Conventional names are optional conveniences; applications declare their own supported names through Environments.

func EnvironmentFromEnv

func EnvironmentFromEnv(fallback Environment) (Environment, error)

EnvironmentFromEnv resolves PFW_ENV, or an explicit application fallback. An explicitly empty PFW_ENV is invalid rather than silently using a fallback.

func (Environment) Validate

func (e Environment) Validate() error

type Registration

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

Registration is a build-time declaration read by the generator.

func AutoBind

func AutoBind(enabled ...bool) Registration

AutoBind configures interface inference at Build/BuildWithCleanup or Module level. No argument means true; false disables inference in that scope. Modules inherit the nearest enclosing setting unless they declare their own.

func Bind

func Bind[Interface, Concrete any]() Registration

Bind is an alias for Implementation, with the same type argument order.

func Constructors

func Constructors(constructors ...any) Registration

Constructors registers named constructor functions, whose parameters are their dependencies. Supported results are T, (T, error), and (T, func() error, error) for resources that need cleanup.

func Discover

func Discover(patterns ...string) Registration

Discover registers functions annotated //pfw:coconut in selected Go package patterns. Relative patterns are resolved from the initializer's package.

func Environments

func Environments(names ...Environment) Registration

Environments declares supported names. It is required for initializers with an Environment parameter; ForEnv names must belong to this explicit set.

func Exclude

func Exclude(constructors ...any) Registration

Exclude removes constructors from discovery, independent of declaration order. Explicit Constructors registrations remain available.

func ForEnv

func ForEnv(name Environment, registrations ...Registration) Registration

ForEnv activates registrations in the named environment only.

func Implementation

func Implementation[Interface, Concrete any]() Registration

Implementation selects Concrete as the implementation of Interface. The generator verifies implementation using Go's type system.

func Module

func Module(registrations ...Registration) Registration

Module groups static registrations without imposing a package layout.

func Override

func Override(registrations ...Registration) Registration

Override gives wrapped constructors precedence in their scope. Manual interface bindings still win; different override candidates remain ambiguous.

Directories

Path Synopsis
cmd
pfw command
Package config loads environment variables into typed application configuration.
Package config loads environment variables into typed application configuration.
examples
cleanup command
httpapi/cmd/api command
Package http provides transport-independent HTTP responses, JSON decoding and application error mapping.
Package http provides transport-independent HTTP responses, JSON decoding and application error mapping.
internal
di
Package di implements the build-time dependency graph used by pfw.
Package di implements the build-time dependency graph used by pfw.
generate
Package generate loads explicit pfw declarations and emits Go initializers.
Package generate loads explicit pfw declarations and emits Go initializers.
scaffold
Package scaffold creates standalone Go projects from bundled templates.
Package scaffold creates standalone Go projects from bundled templates.
Package lifecycle coordinates application components and resource cleanup.
Package lifecycle coordinates application components and resource cleanup.
Package logging provides an injectable logging contract and a standard-library implementation.
Package logging provides an injectable logging contract and a standard-library implementation.
transport
echo
Package echo provides optional helpers for native Echo handlers and middleware.
Package echo provides optional helpers for native Echo handlers and middleware.
httpserver
Package httpserver connects a standard HTTP server to the application lifecycle.
Package httpserver connects a standard HTTP server to the application lifecycle.

Jump to

Keyboard shortcuts

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