happy

package module
v0.305.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2025 License: Apache-2.0 Imports: 12 Imported by: 5

README

Happy Logo

Happy Prototyping Framework and SDK

Happy SDK is an open-source Go framework designed to make building applications simple and fast. Its clear, modular structure and addon system promote code reuse, enabling anyone—coders or non-coders—to create prototypes or full projects efficiently. It integrates smoothly with projects using multiple programming languages, helping teams bring ideas to life with ease with built-in monorepo support.

Until v1.0.0, API changes may break compatibility, so pin your Happy version and update cautiously.

Update your project to latest

go get -u github.com/happy-sdk/happy

GitHub Release PkgGoDev Coverage Status GitHub License

Creating application

Happy SDK is designed to simplify your development process without introducing any new or additional developer tools. Your applications built with Happy can be used, built, and tested with the standard Go build tools, such as 'go test', 'go build', and 'go run'. With Happy, you have complete control over your development environment, as it will not add any third-party dependencies to your project.

Here's a minimal example of how you can use Happy:

// main.go
package main

import (
 "fmt"

 "github.com/happy-sdk/happy"
 "github.com/happy-sdk/happy/sdk/action"
 "github.com/happy-sdk/happy/sdk/session"
)

func main() {
 app := happy.New(nil)

 app.Do(func(sess *session.Context, args action.Args) error {
  sess.Log().Info("Hello, world! ")
  return nil
 })

 app.Run()
}
// go run . 
// OUT: 
// info  00:00:00.000 Hello, world!

Here's a example enabling builtin global flags including (help,version:

// main.go
package main

import (
 "fmt"

 "github.com/happy-sdk/happy"
 "github.com/happy-sdk/happy/sdk/action"
 "github.com/happy-sdk/happy/sdk/session"
)

func main() {
 app := happy.New(&happy.Settings{
  // Engine: happy.EngineSettings{},

  CLI: happy.CliSettings{
   WithGlobalFlags: true,
  },

  // Profiles: happy.ProfileSettings{},
  // DateTime: happy.DateTimeSettings{},
  Instance: happy.InstanceSettings{},

  // We enable global flags which has --verbose flag to set info level
  // so we set default something higher than info
  Logging: happy.LoggingSettings{
   Level: logging.LevelSuccess,
  },

  // Services: happy.ServicesSettings{},
  // Stats:    happy.StatsSettings{},
  // Devel:    happy.DevelSettings{},
  // I18n:     happy.I18nSettings{},
 })

 app.Do(func(sess *session.Context, args action.Args) error {
  sess.Log().Info("Hello, world! ")
  return nil
 })

 app.Run()
}
// go run . -h
// OUT: 
//  Happy Prototype - v0.0.1-devel+git.<hash>.<timestamp>
//  Copyright © {year} Anonymous
//  License: NOASSERTION
//  
//  This application is built using the Happy-SDK to provide enhanced functionality and features.
//
//  yourcmd [flags]
//
// GLOBAL FLAGS:
//
//  --debug              enable debug log level - default: "false"
//  --help         -h    display help or help for the command. [...command --help] - default: "false"
//  --show-exec    -x    the -x flag prints all the cli commands as they are executed. - default: "false"
//  --system-debug       enable system debug log level (very verbose) - default: "false"
//  --verbose      -v    set log level info - default: "false"
//  --version            print application version - default: "false"

For more examples, take a look at the examples section and the examples in the ./examples/ directory.

Examples

Below are a few small examples to help you get started quickly.
You can run them directly from the repository root using go run.

  • Minimal application

    go run ./examples/apps/minimal
    
  • Basic application with built-in CLI features

    go run ./examples/apps/basic
    
  • Application using an addon

    go run ./examples/apps/hello
    
  • Showcase application (multiple features together)

    go run ./examples/apps/showcase
    

See the full source in the ./examples/ directory for more patterns.

Application API

More details of api read happy Godoc
PkgGoDev


...
app.AddInfo(/* add paragraph to app help */)
app.WithOptions(/* adds allowed runtime option */)
app.SetOptions(/* update default value for any application or addon option */) 
app.Setup(/* optional setup action called only first time app is used */)
app.WithAddon(/* adds addon to app */)
app.WithBrand(/* customize branding of the app */)
app.WithCommands(/* adds command(s) to app */)
app.WithFlags(/* adds flag(s) to app root command */)
app.WithLogger(/* uses provided logger */)
app.WithMigrations(/* use migration manager */)
app.WithServices(/* adds service(s) to app */)

...

...
// Application root command actions
app.BeforeAlways(/* called always before any command is invoked*/)
app.Before(/* called before root command is invoked*/)
app.Do(/* root command Do function */)
app.AfterSuccess(/* called when root cmd or sub command returns without errors */)
app.AfterFailure(/* called when root cmd or sub command returns with errors */)
app.AfterAlways(/* called always when root cmd or sub command returns */)
app.Tick(/* called in specific interfal while root command is blocking */)
app.Tock(/* called after every tick*/)
...
Commands

command.Command provides a universal API for attaching sub-commands directly to the application or providing them from an Addon.
PkgGoDev

import "github.com/happy-sdk/happy/sdk/cli/command"
...
cmd := command.New(command.Config{
  Name: "my-command"
})

cmd.Do(/* Main function for the command */)
// Optional:
cmd.Before(/* Called after app.Before and before cmd.Do */)
cmd.AfterSuccess(/* Called when cmd.Do returns without errors */)
cmd.AfterFailure(/* Called when cmd.Do returns with errors */)
cmd.AfterAlways(/* Called always when cmd.Do returns */)

cmd.Usage(/* add attitional usage lines to help menu */)
cmd.AddInfo(/* add long description paragraph for command */)
cmd.WithSubCommands(/* Add a sub-command to the command */)
cmd.WithFlags(/* add flag(s) to  command*/)
...
Services

The services.Service API provides a flexible way to add runtime-controllable background services to your application.
PkgGoDev

import (
  "github.com/happy-sdk/happy/sdk/services"
  "github.com/happy-sdk/happy/sdk/services/service"
)
...
svc := services.New(service.Config{
  Name: "my-service",
})

svc.OnRegister(/* Called when the app starts. */)
svc.OnStart(/* Called when the service is requested to start. */)
svc.OnStop(/* Called when the service is requested to stop. */)
svc.OnEvent(/* Called when a specific event is received. */)
svc.OnAnyEvent(/* Called when any event is received. */)
svc.Cron(/* Scheduled cron jobs to run when the service is running. */)
svc.Tick(/* Called every tick when the service is running. */)
svc.Tock(/* Called after every tick when the service is running. */)

app.WithServices(svc)
...

Addons

Addons provide a simple way to bundle commands and services into a single Go package, allowing for easy sharing between projects.
PkgGoDev

// main.go
package main

import (
  "github.com/happy-sdk/happy"
  "helloworld"
)

func main() {
  app := happy.New(&happy.Settings{})
  app.WithAddons(helloworld.Addon())
  app.Run()
}

// helloworld/addon.go
package helloworld

import (
  "github.com/happy-sdk/happy/sdk/addon"
  "github.com/happy-sdk/happy/sdk/session"
  "github.com/happy-sdk/happy/sdk/custom"
)

type HelloWorldAPI struct {
  custom.API
}

func Addon() *happy.Addon {
  ad := addon.New("Hello World").
    WithOptions(
      addon.Option("my-opt", "default-val"),
    )


  // Optional: Register commands provided by the addon
  ad.ProvideCommands(/* provide command(s) */)

  // Optional: Register services provided by the addon
  ad.ProvideServices(/* provide service(s) */)

  // Optional: Make a custom API accessible across the application 
  ad.ProvideAPI(&HelloWorldAPI{}) 

  // Register all events that the addon may emit ()
  ad.WithEvents(/* events what addon emits */)

  // Optional callback to be called when the addon is registered
  ad.OnRegister(func(sess session.Register) error {
    sess.Log().Notice("hello-world addon registered")
    return nil
  })

  return ad
}

Credits

GitHub contributors

Happy banner design.
Happy banner was designed by Egon Elbre egonelbre.com

Documentation

Overview

Package happy provides a modular framework for rapid prototyping in Go. With this SDK, developers of all levels can easily bring their ideas to life. Whether you're a hacker or a creator, Package happy has everything you need to tackle your domain problems and create working prototypes or MVPs with minimal technical knowledge and infrastructure planning.

Its modular design enables you to package your commands and services into reusable addons, so you're not locked into any vendor tools. It also fits well into projects where different components are written in different programming languages.

Let Package happy help you bring your projects from concept to reality and make you happy along the way.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotImplemented = errors.New("not implemented")

Functions

func API

func API[API api.Provider](sess *session.Context) (api API, err error)

API returns the API for the given type if it is registered.

func New

func New(c *Settings, extend ...settings.Settings) *app.Main

func ServiceLoader

func ServiceLoader(sess *session.Context, svcs ...string) *services.ServiceLoader

ServiceLoader is a convenience function to create a new ServiceLoader instance from the services package. It initializes and prepares the specified services for loading using the provided session context, acting as a shorthand for services.NewLoader within the Happy-SDK framework.

Parameters:

  • sess: The session context used to configure the service loader.
  • svcs: A variadic list of service names or addresses to be loaded and started.

Returns:

  • A pointer to a ServiceLoader instance configured to load the specified services.

Example usage:

loader := ServiceLoader(sess, "serviceA", "serviceB")
<-loader.Load()
if err := loader.Err(); err != nil {
    log.Fatal("Service loading failed:", err)
}

Types

type CliSettings added in v0.100.0

type CliSettings struct {
	settings.Settings
	MainMinArgs          settings.Uint `default:"0" desc:"Minimum number of arguments for a application main"`
	MainMaxArgs          settings.Uint `default:"0" desc:"Maximum number of arguments for a application main"`
	WithConfigCmd        settings.Bool `default:"false" desc:"Add the config command in the CLI"`
	WithI18nCmd          settings.Bool `default:"false" desc:"Add the i18n command in the CLI"`
	WithGlobalFlags      settings.Bool `default:"false" desc:"Add the default global flags automatically in the CLI"`
	HideDisabledCommands settings.Bool `default:"false" desc:"Hide disabled commands"`
}

func (CliSettings) Blueprint added in v0.100.0

func (s CliSettings) Blueprint() (*settings.Blueprint, error)

type DateTimeSettings added in v0.100.0

type DateTimeSettings struct {
	Location settings.String `key:"location,save" default:"Local" mutation:"once" desc:"The location to use for time operations."`
}

func (DateTimeSettings) Blueprint added in v0.100.0

func (s DateTimeSettings) Blueprint() (*settings.Blueprint, error)

type DevelSettings added in v0.100.0

type DevelSettings struct {
	AllowProd settings.Bool `default:"false" desc:"Allow set app into production mode when running from source."`
}

Settings for the devel module. These settings are used to configure the behavior of the application when user compiles your application from source or uses go run .

func (DevelSettings) Blueprint added in v0.100.0

func (s DevelSettings) Blueprint() (*settings.Blueprint, error)

type EngineSettings added in v0.100.0

type EngineSettings struct {
	ThrottleTicks settings.Duration `key:"throttle_ticks,save" default:"1s" mutation:"once" desc:"Throttle engine ticks duration"`
}

func (*EngineSettings) Blueprint added in v0.100.0

func (s *EngineSettings) Blueprint() (*settings.Blueprint, error)

type I18nSettings added in v0.100.0

type I18nSettings struct {
	Language  settings.String      `key:"language,save" default:"en" mutation:"mutable"`
	Supported settings.StringSlice `key:"supported"`
}

Settings represents the configuration settings for internationalization. It provides a blueprint for configuring the default language and supported languages for Happy SDK Applications.

func (I18nSettings) Blueprint added in v0.100.0

func (s I18nSettings) Blueprint() (*settings.Blueprint, error)

type InstanceSettings added in v0.100.0

type InstanceSettings struct {
	// How many instances of the applications can be booted at the same time.
	Max settings.Uint `` /* 132-byte string literal not displayed */
}

func (InstanceSettings) Blueprint added in v0.100.0

func (s InstanceSettings) Blueprint() (*settings.Blueprint, error)

type LoggingSettings added in v0.100.0

type LoggingSettings struct {
	Level           logging.Level   `key:"level,config" default:"info" mutation:"mutable" desc:"logging level"`
	WithSource      settings.Bool   `key:"with_source,config" default:"false" mutation:"once" desc:"Show source location in log messages"`
	TimestampFormat settings.String `key:"timeestamp_format,config" default:"15:04:05.000" mutation:"once" desc:"Timestamp format for log messages"`
	NoTimestamp     settings.Bool   `key:"no_timestamp,config" default:"false" mutation:"once" desc:"Do not show timestamps"`
	NoSlogDefault   settings.Bool   `key:"no_slog_default" default:"false" mutation:"once" desc:"Do not set the default slog logger"`
}

func (LoggingSettings) Blueprint added in v0.100.0

func (s LoggingSettings) Blueprint() (*settings.Blueprint, error)

type ProfileSettings added in v0.100.0

type ProfileSettings struct {
	// Disabled is used to disable the configuration system. When set to true, the configuration
	// system is disabled and single runtime profile is used. This is useful when the application does not
	// require user configuration and only uses the default settings.
	// All settings below are ignored and set to default values when Disabled is set to true.
	Disabled    settings.Bool        `default:"false" desc:"Disabled presistent user configuration"`
	Additional  settings.StringSlice `desc:"Additional profiles provided by default."`
	Default     settings.String      `default:"default" mutation:"once" desc:"Default profile to use when no profile is specified."`
	AllowCustom settings.Bool        `default:"false" desc:"Are creation of custom profiles allowed."`

	// EnableProfileDevel enables profile development mode. This mode allows different settings
	// for development and release versions for a named profile. When this flag is set to true,
	// a profile named "default" will also have a corresponding "default-devel" profile.
	//
	// In development mode (e.g., when using `go run` or a locally compiled binary), the "-devel"
	// profile is used. In release mode, the standard profile is used.
	//
	// If application Devel.AllowProd is set to true, this behavior can be overridden by using
	// the -x-prod flag, which is added by the devel package when the AllowProd option is enabled.
	// This allows to load the standard profile even when running in development mode e.g. go run.
	EnableDevel settings.Bool `default:"false" desc:"Enable profile development mode."`
}

func (ProfileSettings) Blueprint added in v0.100.0

func (s ProfileSettings) Blueprint() (*settings.Blueprint, error)

type ServicesSettings added in v0.100.0

type ServicesSettings struct {
	LoaderTimeout  settings.Duration `key:"loader_timeout,save" default:"30s" mutation:"once" desc:"Service loader timeout"`
	RunCronOnStart settings.Bool     `key:"cron_on_service_start,save" default:"false" mutation:"once" desc:"Run cron jobs on service start"`
}

func (ServicesSettings) Blueprint added in v0.100.0

func (s ServicesSettings) Blueprint() (*settings.Blueprint, error)

type Settings added in v0.11.0

type Settings struct {

	// Appication info
	Name           settings.String `key:"app.name" default:"Happy Prototype" desc:"Application name"`
	Slug           settings.String `key:"app.slug" default:"" desc:"Application slug"`
	Identifier     settings.String `key:"app.identifier" desc:"Application identifier"`
	Description    settings.String `key:"app.description" desc:"Application description" i18n:"true"`
	CopyrightBy    settings.String `key:"app.copyright_by" default:"Anonymous" desc:"Application author"`
	CopyrightSince settings.Uint   `key:"app.copyright_since" default:"0" desc:"Application copyright since"`
	License        settings.String `key:"app.license" default:"NOASSERTION" desc:"Application license"`

	// Application settings
	Engine   EngineSettings   `key:"app.engine"`
	CLI      CliSettings      `key:"app.cli"`
	Profiles ProfileSettings  `key:"app.profiles"`
	DateTime DateTimeSettings `key:"app.datetime"`
	Instance InstanceSettings `key:"app.instance"`
	Logging  LoggingSettings  `key:"app.logging"`
	Services ServicesSettings `key:"app.services"`
	Stats    StatsSettings    `key:"app.stats"`
	Devel    DevelSettings    `key:"app.devel"`
	I18n     I18nSettings     `key:"app.i18n"`
	// contains filtered or unexported fields
}

func (*Settings) Blueprint added in v0.11.0

func (s *Settings) Blueprint() (*settings.Blueprint, error)

func (*Settings) GetFallbackLanguage added in v0.100.0

func (s *Settings) GetFallbackLanguage() string

func (*Settings) Migrate added in v0.15.0

func (s *Settings) Migrate(keyfrom, keyto string) *Settings

Migrate allows auto migrate old settings from keyfrom to keyto when applying preferences from deprecated keyfrom.

type StatsSettings added in v0.100.0

type StatsSettings struct {
	Enabled settings.Bool `key:"enabled,save" default:"false" mutation:"once"  desc:"Enable runtime statistics"`
}

func (StatsSettings) Blueprint added in v0.100.0

func (s StatsSettings) Blueprint() (*settings.Blueprint, error)

Directories

Path Synopsis
addons
cmd
hap module
examples
addons/hello
SPDX-License-Identifier: Apache-2.0
SPDX-License-Identifier: Apache-2.0
apps/basic command
SPDX-License-Identifier: Apache-2.0
SPDX-License-Identifier: Apache-2.0
apps/hello command
SPDX-License-Identifier: Apache-2.0
SPDX-License-Identifier: Apache-2.0
apps/minimal command
SPDX-License-Identifier: Apache-2.0
SPDX-License-Identifier: Apache-2.0
apps/showcase command
SPDX-License-Identifier: Apache-2.0
SPDX-License-Identifier: Apache-2.0
internal
cmd/hap module
pkg
bitutils module
branding module
bytesize module
cli/ansicolor module
devel/goutils module
fsutils module
i18n module
logging module
networking module
options module
settings module
strings/bexp module
strings/slug module
tui module
vars module
version module
sdk
api
app
cli
Package cli provides utilities for happy command line interfaces.
Package cli provides utilities for happy command line interfaces.
tools

Jump to

Keyboard shortcuts

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