app_settings

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: May 3, 2026 License: GPL-3.0 Imports: 19 Imported by: 0

README

App Settings Package

The app_settings package provides a standardized way to register, manage, and persist application settings. It supports integration with a Kong-based CLI interface and optional RPC access for listing live in-memory settings.

Features

  • Register settings dynamically from any package
  • Save and remove settings via CLI
  • List default, saved, and running settings
  • Retrieve current values programmatically
  • Integrate with Kong CLI commands
  • Expose settings via RPC socket (optional)

Installation

Import the module in your Go project:

import "github.com/dan-sherwin/go-app-settings"

Setup

Call Setup() early in your application initialization:

vars := kong.Vars{}
err := app_settings.Setup("myapp.db", app_settings.SettingsOptions{
    RpcSocketPathToListRunningSettings: "/tmp/myapp.sock",
    KongVars:                           &vars,
})
if err != nil {
    log.Fatalf("setup failed: %v", err)
}

If your application already owns a GORM database and you want app_settings to share that database, use SetupWithDB():

gormDB, err := gorm.Open(sqlite.Open("myapp.db"), &gorm.Config{})
if err != nil {
    log.Fatalf("open db failed: %v", err)
}

// Migrate application tables first.
if err := gormDB.AutoMigrate(&LaunchItem{}, &LaunchGroup{}); err != nil {
    log.Fatalf("app migration failed: %v", err)
}

if err := app_settings.SetupWithDB(gormDB, app_settings.SettingsOptions{}); err != nil {
    log.Fatalf("settings setup failed: %v", err)
}

By default, the settings table is named app_settings. If your application already has an incompatible table by that name, setup returns an error. Use SettingsOptions.TableName to store settings in a different table:

err := app_settings.SetupWithDB(gormDB, app_settings.SettingsOptions{
    TableName: "runtime_settings",
})

Registering Settings

You can register settings either by providing a Setting directly or by implementing the SettingReceiver interface.

Option 1: Direct Registration
var foobar string

app_settings.RegisterSetting(&app_settings.Setting{
    Name:        "foobar",
    Description: "The setting of foobar",
    GetFunc: func() string { return foobar },
    SetFunc: func(s string) error {
        foobar = s
        return nil
    },
})

Settings can be hidden from Kong settings commands while remaining available to application code:

app_settings.RegisterSetting(&app_settings.Setting{
    Name:        "internal_token",
    Description: "Internal token",
    Hidden:      true,
    GetFunc:     func() string { return internalToken },
    SetFunc: func(s string) error {
        internalToken = s
        return nil
    },
})

Hidden settings are loaded from the database and can be changed with app_settings.SetSetting(...), but they are excluded from settings list ... commands and cannot be saved or removed through the settings CLI.

Option 2: Struct-Based Receiver
type Feebar struct{}

func (Feebar) SettingName() string        { return "feebar" }
func (Feebar) SettingDescription() string { return "The setting of feebar" }
func (Feebar) SettingSet(s string) error  { feebar = s; return nil }
func (Feebar) SettingGet() string         { return feebar }

func init() {
    app_settings.RegisterSettingReceiver(&Feebar{})
}

Kong CLI Integration

Add SettingsDef to your Kong configuration struct:

var CLIConfig struct {
    app_settings.SettingsDef
    // your other commands
}

Kong will automatically wire in the following CLI structure:

myapp settings list defaults
myapp settings list saved
myapp settings list running
myapp settings save <setting> <value>
myapp settings remove <setting>

Retrieving Settings in Code

To retrieve the current value of a setting programmatically:

val := app_settings.SettingsVars()["foobar"]

RPC Access

If RpcSocketPathToListRunningSettings is specified in Setup(), the running settings can be accessed via RPC. This enables external tooling or dashboards to introspect current config state at runtime.

client, _ := rpc.Dial("unix", "/tmp/myapp.sock")
var running []models.AppSetting
client.Call("SettingsListRunningCommand.GetRunningSettings", &struct{}{}, &running)

Registration Helper Functions

RegisterBoolSetting

func RegisterBoolSetting(name, description string, prop *bool)

Registers a boolean setting with a specified name, description, and pointer to the bool property.

RegisterDurationSetting

func RegisterDurationSetting(name, description string, prop *time.Duration)

Registers a time.Duration setting with a specified name, description, and pointer to the time.Duration property.

RegisterFloat32Setting

func RegisterFloat32Setting(name, description string, prop *float32)

Registers a 32-bit float setting with a specified name, description, and pointer to the float32 property.

RegisterFloatSetting

func RegisterFloatSetting(name, description string, prop *float64)

Registers a float64 setting with a specified name, description, and pointer to the float64 property.

RegisterInt32Setting

func RegisterInt32Setting(name, description string, prop *int32)

Registers a 32-bit integer setting with a specified name, description, and pointer to the int32 property.

RegisterInt64Setting

func RegisterInt64Setting(name, description string, prop *int64)

Registers a 64-bit integer setting with a specified name, description, and pointer to the int64 property.

RegisterInt8Setting

func RegisterInt8Setting(name, description string, prop *int8)

Registers an 8-bit integer setting with a specified name, description, and pointer to the int8 property.

RegisterIntSetting

func RegisterIntSetting(name, description string, prop *int)

Registers an integer setting with a specified name, description, and pointer to the int property.

RegisterIPNetSetting

func RegisterIPNetSetting(name, description string, prop *net.IPNet)

Registers a net.IPNet setting (CIDR format) with a specified name, description, and pointer to the net.IPNet property.

RegisterIPSetting

func RegisterIPSetting(name, description string, prop *net.IP)

Registers a net.IP setting with a specified name, description, and pointer to the net.IP property.

RegisterStringSetting

func RegisterStringSetting(name, description string, prop *string)

Registers a string setting with a specified name, description, and pointer to the string property.

RegisterJSONSetting

func RegisterJSONSetting[T any](name, description string, prop *T)

Registers a JSON setting backed by a typed Go value. Values are stored as JSON text in the settings table.

RegisterJSONSettingWithValidator

func RegisterJSONSettingWithValidator[T any](name, description string, prop *T, validate func(T) error)

Registers a JSON setting and validates decoded values before applying them.

RegisterStringSliceSetting

func RegisterStringSliceSetting(name, description string, prop *[]string)

Registers a string slice setting (comma-separated) with a specified name, description, and pointer to the []string property.

RegisterTimeSetting

func RegisterTimeSetting(name, description string, prop *time.Time)

Registers a time.Time setting (RFC3339 format) with a specified name, description, and pointer to the time.Time property.

RegisterUint16Setting

func RegisterUint16Setting(name, description string, prop *uint16)

Registers a 16-bit unsigned integer setting with a specified name, description, and pointer to the uint16 property.

RegisterUint32Setting

func RegisterUint32Setting(name, description string, prop *uint32)

Registers a 32-bit unsigned integer setting with a specified name, description, and pointer to the uint32 property.

RegisterUint64Setting

func RegisterUint64Setting(name, description string, prop *uint64)

Registers a 64-bit unsigned integer setting with a specified name, description, and pointer to the uint64 property.

RegisterUint8Setting

func RegisterUint8Setting(name, description string, prop *uint8)

Registers an 8-bit unsigned integer setting with a specified name, description, and pointer to the uint8 property.

RegisterUintSetting

func RegisterUintSetting(name, description string, prop *uint)

Registers an unsigned integer setting with a specified name, description, and pointer to the uint property.

RegisterURLSetting

func RegisterURLSetting(name, description string, prop *url.URL)

Registers a url.URL setting with a specified name, description, and pointer to the url.URL property.


Testing

This repository includes unit tests that can be executed locally and in any CI environment that has Go installed.

  • Minimum Go version: 1.22
  • Run all tests:
go test ./...

The tests use a temporary on-disk SQLite database via GORM; no external services are required. They also capture stdout for commands that print tables.

Example: GitHub Actions CI

If you want to run the tests in GitHub Actions, you can use a minimal workflow like this:

name: go-test
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version: '1.22.x'
      - run: go test ./...

License

ISC

Documentation

Index

Constants

View Source
const DefaultTableName = models.TableNameAppSetting

Variables

This section is empty.

Functions

func RegisterBoolSetting

func RegisterBoolSetting(name string, description string, prop *bool)

RegisterBoolSetting registers a boolean setting with a specified name, description, and pointer to the bool property.

func RegisterCronSetting

func RegisterCronSetting(name, description string, cronString *string)

func RegisterDurationSetting

func RegisterDurationSetting(name string, description string, prop *time.Duration)

RegisterDurationSetting registers a time.Duration setting with a specified name, description, and pointer to the time.Duration property.

func RegisterFloat32Setting

func RegisterFloat32Setting(name string, description string, prop *float32)

RegisterFloat32Setting registers a 32-bit float setting with a specified name, description, and pointer to the float32 property.

func RegisterFloatSetting

func RegisterFloatSetting(name string, description string, prop *float64)

RegisterFloatSetting registers a float64 setting with a specified name, description, and pointer to the float64 property.

func RegisterIPNetSetting

func RegisterIPNetSetting(name, description string, prop *net.IPNet)

RegisterIPNetSetting registers a net.IPNet setting (CIDR format).

func RegisterIPSetting

func RegisterIPSetting(name, description string, prop *net.IP)

RegisterIPSetting registers a net.IP setting.

func RegisterInt8Setting

func RegisterInt8Setting(name, description string, prop *int8)

RegisterInt8Setting registers an 8-bit integer setting.

func RegisterInt16Setting

func RegisterInt16Setting(name, description string, prop *int16)

RegisterInt16Setting registers a 16-bit integer setting.

func RegisterInt32Setting

func RegisterInt32Setting(name string, description string, prop *int32)

RegisterInt32Setting registers a 32-bit integer setting with a specified name, description, and pointer to the int32 property.

func RegisterInt64Setting

func RegisterInt64Setting(name string, description string, prop *int64)

RegisterInt64Setting registers a 64-bit integer setting with a specified name, description, and pointer to the int64 property.

func RegisterIntSetting

func RegisterIntSetting(name string, description string, prop *int)

RegisterIntSetting registers an integer setting with a name, description, and a pointer to the integer property.

func RegisterJSONSetting added in v0.4.0

func RegisterJSONSetting[T any](name, description string, prop *T)

func RegisterJSONSettingWithValidator added in v0.4.0

func RegisterJSONSettingWithValidator[T any](name, description string, prop *T, validate func(T) error)

func RegisterSetting

func RegisterSetting(s *Setting)

RegisterSetting adds a given Setting to the global settings list.

func RegisterSettingReceiver

func RegisterSettingReceiver(r SettingReceiver)

RegisterSettingReceiver registers a SettingReceiver by wrapping its methods in a Setting struct and appending it to the global settings list.

func RegisterStringSetting

func RegisterStringSetting(name string, description string, prop *string)

RegisterStringSetting registers a string setting with a specified name, description, and a pointer to the property to manage its value.

func RegisterStringSliceSetting

func RegisterStringSliceSetting(name, description string, prop *[]string)

RegisterStringSliceSetting registers a string slice setting (comma-separated).

func RegisterTimeSetting

func RegisterTimeSetting(name, description string, prop *time.Time)

RegisterTimeSetting registers a time.Time setting using RFC3339 format.

func RegisterURLSetting

func RegisterURLSetting(name, description string, prop *url.URL)

RegisterURLSetting registers a url.URL setting.

func RegisterUint8Setting

func RegisterUint8Setting(name, description string, prop *uint8)

RegisterUint8Setting registers an 8-bit unsigned integer setting.

func RegisterUint16Setting

func RegisterUint16Setting(name, description string, prop *uint16)

RegisterUint16Setting registers a 16-bit unsigned integer setting.

func RegisterUint32Setting

func RegisterUint32Setting(name, description string, prop *uint32)

RegisterUint32Setting registers a 32-bit unsigned integer setting.

func RegisterUint64Setting

func RegisterUint64Setting(name, description string, prop *uint64)

RegisterUint64Setting registers a 64-bit unsigned integer setting.

func RegisterUintSetting

func RegisterUintSetting(name string, description string, prop *uint)

RegisterUintSetting registers an unsigned integer setting with a specified name, description, and pointer to the uint property.

func RetrieveAppSettings

func RetrieveAppSettings() error

RetrieveAppSettings fetches application settings from the database and initializes default settings. If database retrieval fails, the application exits with an error. It also updates in-memory settings based on the retrieved values from the database.

func SetSetting added in v0.2.0

func SetSetting(settingName string, value any) error

SetSetting updates the value of a specified setting by its name. Converts the provided value to a string and applies it using the setting's SetFunc. Saves the updated setting to the database and returns an error if any operation fails.

func SettingsVars

func SettingsVars() kong.Vars

SettingsVars constructs a kong.Vars map by iterating through all settings, retrieving their values using associated getters, and populating the map with setting names as keys and their retrieved values as values.

func Setup

func Setup(settingsFileName string, options SettingsOptions) error

Setup initializes the application with the provided settings file and options. It configures the database, sets up the RPC socket if specified, merges Kong variables, and retrieves application settings. Returns an error if any initialization step fails.

func SetupWithDB added in v0.4.0

func SetupWithDB(gormDB *gorm.DB, options SettingsOptions) error

Types

type Setting

type Setting struct {
	SetFunc           func(string) error
	GetFunc           func() string
	ValueToStringFunc func(any) (string, error)
	Name              string
	Description       string
	Hidden            bool
}

SettingsOptions defines configuration options for listing running settings.

func GetSetting added in v0.2.0

func GetSetting(name string) (*Setting, error)

GetSetting retrieves a `Setting` by its name from the global list `settings`. If no match is found, it returns `nil`.

func (*Setting) ValueToString added in v0.4.0

func (s *Setting) ValueToString(value any) (string, error)

type SettingReceiver

type SettingReceiver interface {
	SettingName() string
	SettingDescription() string
	SettingSet(string) error
	SettingGet() string
}

SettingsOptions defines configuration options for listing running settings.

type SettingsCommand

type SettingsCommand struct {
	List   SettingsListCommand   `cmd:"" help:"List settings"`
	Save   SettingsSaveCommand   `cmd:"" help:"Save settings"`
	Set    SettingsSaveCommand   `cmd:"" help:"Alias for save"`
	Remove SettingsRemoveCommand `cmd:"" help:"Remove settings"`
	Unset  SettingsRemoveCommand `cmd:"" help:"Alias for remove"`
}

SettingsOptions defines configuration options for listing running settings.

type SettingsDef

type SettingsDef struct {
	Logging struct {
		Level string `enum:"debug,info,warn,error" default:"${logging_level}" help:"debug, info, warn, error" group:"logging"`
	} `embed:"" prefix:"logging."`
	Settings SettingsCommand `cmd:"" help:"Settings" group:"App Settings"`
}

SettingsOptions defines configuration options for listing running settings.

type SettingsListActiveCommand

type SettingsListActiveCommand struct{}

SettingsOptions defines configuration options for listing running settings.

func (*SettingsListActiveCommand) Run

type SettingsListCommand

type SettingsListCommand struct {
	Defaults SettingsListDefaultsCommand `cmd:"" help:"List default settings"`
	Saved    SettingsListSavedCommand    `cmd:"" help:"List saved settings"`
	Running  SettingsListRunningCommand  `cmd:"" help:"List running settings"`
	Active   SettingsListActiveCommand   `cmd:"" help:"List active settings"`
}

SettingsOptions defines configuration options for listing running settings.

type SettingsListDefaultsCommand

type SettingsListDefaultsCommand struct{}

SettingsOptions defines configuration options for listing running settings.

func (*SettingsListDefaultsCommand) Run

Run executes the command to display default application settings in a sorted table format. It uses the printSettings function to handle the output of pre-defined settings. Returns nil upon successful execution.

type SettingsListRunningCommand

type SettingsListRunningCommand struct{}

SettingsOptions defines configuration options for listing running settings.

func (*SettingsListRunningCommand) GetRunningSettings

func (c *SettingsListRunningCommand) GetRunningSettings(_ *struct{}, data *[]models.AppSetting) error

GetRunningSettings retrieves the current running application settings and maps them into a slice of AppSetting. The result is assigned to the provided data pointer. Returns an error if the operation fails.

func (*SettingsListRunningCommand) Run

Run connects to a Unix socket, retrieves running application settings via RPC, processes them, and displays them. It returns an error if the connection fails or if settings retrieval is unsuccessful.

type SettingsListSavedCommand

type SettingsListSavedCommand struct{}

SettingsOptions defines configuration options for listing running settings.

func (*SettingsListSavedCommand) Run

Run executes the command to retrieve and display saved settings. It fetches settings from the database, handles errors, and prints the retrieved settings to the console. Returns an error if there is an issue during the retrieval process.

type SettingsOptions

type SettingsOptions struct {
	RpcSocketPathToListRunningSettings string
	KongVars                           *kong.Vars
	TableName                          string
}

SettingsOptions defines configuration options for listing running settings.

type SettingsRemoveCommand

type SettingsRemoveCommand struct {
	Setting string `arg:"" help:"Setting to remove" required:""`
}

SettingsOptions defines configuration options for listing running settings.

func (*SettingsRemoveCommand) Run

func (c *SettingsRemoveCommand) Run() error

Run removes the specified application setting if it exists, otherwise returns an error. It identifies the setting by name, deletes it from the database, and handles any errors encountered during the operation. On success, it prints a confirmation message.

type SettingsSaveCommand

type SettingsSaveCommand struct {
	Setting string `arg:"" help:"Setting to set" required:""`
	Value   string `arg:"" help:"Value to set" required:""`
}

SettingsOptions defines configuration options for listing running settings.

func (*SettingsSaveCommand) Run

func (c *SettingsSaveCommand) Run() error

Run executes the command to update a specific application setting with a provided value and persists it in the database.

Directories

Path Synopsis
db

Jump to

Keyboard shortcuts

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