main API

main

package

API reference for the main package.

S
struct

CLI

CLI is the root application struct.

examples/main.go:12-21
type CLI struct

Methods

Before
Method

Returns

error
func (*CLI) Before() error
{
	if c.Verbose {
		c.Logger.Info("Verbose mode enabled")
	}
	return nil
}

Fields

Name Type Description
Verbose bool cli:"verbose,v" help:"Enable verbose output" env:"VERBOSE"
Add AddCmd cmd:"" help:"Add a new item to the list"
Remove RemoveCmd cmd:"" help:"Remove an item from the list"
List ListCmd cmd:"" help:"List all items"
F
function

loadItems

Returns

[]string
error
examples/main.go:33-46
func loadItems() ([]string, error)

{
	if _, err := os.Stat(dbFile); os.IsNotExist(err) {
		return []string{}, nil
	}
	data, err := os.ReadFile(dbFile)
	if err != nil {
		return nil, err
	}
	var items []string
	if err := json.Unmarshal(data, &items); err != nil {
		return nil, err
	}
	return items, nil
}
F
function

saveItems

Parameters

items
[]string

Returns

error
examples/main.go:48-54
func saveItems(items []string) error

{
	data, err := json.MarshalIndent(items, "", "  ")
	if err != nil {
		return err
	}
	return os.WriteFile(dbFile, data, 0644)
}
S
struct

AddCmd

AddCmd adds an item.

examples/main.go:57-61
type AddCmd struct

Methods

Run
Method

Returns

error
func (*AddCmd) Run() error
{
	items, err := loadItems()
	if err != nil {
		return err
	}
	items = append(items, c.Item)
	if err := saveItems(items); err != nil {
		return err
	}
	c.Logger.Success("Adding item: %s", c.Item)
	return nil
}

Fields

Name Type Description
Item string arg:"" required:"true" help:"Item to add"
S
struct

RemoveCmd

RemoveCmd removes an item.

examples/main.go:77-81
type RemoveCmd struct

Methods

Run
Method

Returns

error
func (*RemoveCmd) Run() error
{
	items, err := loadItems()
	if err != nil {
		return err
	}
	newItems := []string{}
	found := false
	for _, item := range items {
		if item == c.Item {
			found = true
			continue
		}
		newItems = append(newItems, item)
	}

	if !found {
		c.Logger.Warning("Item not found: %s", c.Item)
		return nil
	}

	if err := saveItems(newItems); err != nil {
		return err
	}
	c.Logger.Success("Removed item: %s", c.Item)
	return nil
}

Fields

Name Type Description
Item string arg:"" required:"true" help:"Item to remove"
S
struct

ListCmd

ListCmd lists all items.

examples/main.go:111-113
type ListCmd struct

Methods

Run
Method

Returns

error
func (*ListCmd) Run() error
{
	items, err := loadItems()
	if err != nil {
		return err
	}
	c.Logger.Info("Listing items...")
	if len(items) == 0 {
		fmt.Println("(no items)")
		return nil
	}
	for _, item := range items {
		fmt.Printf("- %s\n", item)
	}
	return nil
}
F
function

main

examples/main.go:131-137
func main()

{
	app := &CLI{}
	if err := cli.Run(app); err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
		os.Exit(1)
	}
}