gocli

package module
v0.12.3 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2024 License: BSD-2-Clause Imports: 18 Imported by: 12

README

gocli

Entry point for application

Features

  1. Support environment configs with dependencies. Each yaml config file may contain depends key to preload configs from parent environment config files
  2. Support argument customization via config You can define your own flags parsed automatically on application starts
  3. Support processing commands through socket connection You can define your own command passed through socket connection. Command implementation
  4. Logger interface Minimal function set for basic logger
  5. Standard application instance (DNApp) out of the box.

Usage

  1. Define stage config(global.yaml and local.yaml with depends on global.yaml) global.yaml
    depends:
    project:
      name: dna
      debug: false
    web:
      port: 8080
      host: 0.0.0.0
    arguments:
      app:
        type: string
        label: application type
      script:
        type: string
        label: console command name
      consumer:
        type: string
        label: consumer name
      count:
        type: int
        label: count
      success:
        type: bool
        lable: success
    
    local.yaml
    depends: global
      project:
        debug: true
    
  2. Define golang config file with structure for defined config
    type Config struct {
        Project struct {
            Name  string
            Debug bool
        }
        Web struct {
            Port int
            Host string
        }
        Arguments gocli.Arguments
    }
    
  3. Init application
    var config Config
    environment := os.Getenv("ENV")
    if environment == "" {
       environment = "local"
    }
    rootPath, err := filepath.Abs("")
    if err != nil {
        panic(err)
    }
    app := gocli.NewApplication(environment, rootPath+"/config/yaml", &config)
    app.ParseFlags(&config.Arguments)
    
    appType, ok := config.Arguments["app"]
    if ok != true {
        app.FatalError(errors.New("app type is not presents"))
    }
    
  4. Listen command port
    exit := make(chan, struct{})
    go func() {
        err = app.Start(":3333", func(command *gocli.Command) {
            v := command.Arguments()[0]
            app.SuccessMessage("Receive command: "+command.String(), command)
            if v.Name == "exit" {
                app.AttentionMessage("Exit...", command)
                exit <- struct{}{}
            } else if v.Name == "show" {
                app.AttentionMessage(gohelp.AnsiYellow+"The show is began"+gohelp.AnsiReset, command)
            } else {
                app.AttentionMessage(gohelp.AnsiRed+"Unknown command: "+command.String()+gohelp.AnsiReset, command)
            }
        })
    }()
    <- exit
    
If you find this project useful or want to support the author, you can send tokens to any of these wallets
  • Bitcoin: bc1qgx5c3n7q26qv0tngculjz0g78u6mzavy2vg3tf
  • Ethereum: 0x62812cb089E0df31347ca32A1610019537bbFe0D
  • Dogecoin: DET7fbNzZftp4sGRrBehfVRoi97RiPKajV

Documentation

Index

Constants

View Source
const (
	ArgumentTypeString = "string"
	ArgumentTypeInt    = "int"
	ArgumentTypeUint   = "uint"
	ArgumentTypeBool   = "bool"
)
View Source
const (
	CommandPrefix    = "-"
	CommandAssignee  = "="
	CommandDelimiter = ";"
)
View Source
const (
	LogLevelDebug = 1 << iota
	LogLevelInfo
	LogLevelWarn
	LogLevelErr

	DefaultCallDepth = 3

	DefaultKeyLoggerPrefix = "prefix"
)
View Source
const (
	CommandSessionHost = "localhost"
	CommandSessionPort = "8080"
	CommandSessionType = "tcp"
)

Variables

View Source
var (
	// Depends config files
	RegExpDepends, _ = regexp.Compile(`depends:(.*)`)
	// ENV variables in config
	RegExpENV, _ = regexp.Compile(`\$\{(.*)\}`)
)

Functions

This section is empty.

Types

type Application

type Application interface {
	// GetConfig Get config struct
	GetConfig() interface{}
	// GetConfigPath Get full path to config
	GetConfigPath(env string) string
	// GetAbsolutePath Get absolute path
	GetAbsolutePath(path string, dir string) (string, porterr.IError)
	// SetConfig Set config struct
	SetConfig(cfg interface{}) Application
	// ParseConfig Parse config
	ParseConfig(env string) Application
	// Start run application
	Start(port string, callback func(command *Command)) porterr.IError
	// FatalError Behaviour for fatal errors
	FatalError(err error)
	// GetLogger Get Logger
	GetLogger() Logger
	// SetLogger set custom logger
	SetLogger(logger Logger)
	// SuccessMessage Success log message with command repeat
	SuccessMessage(message string, command ...*Command)
	// AttentionMessage Warning log message with command repeat
	AttentionMessage(message string, command ...*Command)
	// FailMessage Fail log message with command repeat
	FailMessage(message string, command ...*Command)
	// ParseFlags Parse console flags
	ParseFlags(args *Arguments)
}

Application interface

func NewApplication added in v0.5.0

func NewApplication(env string, configPath string, values interface{}) Application

NewApplication Create new Application

type Argument

type Argument struct {
	// Type of argument
	Type string
	// Value of argument
	Value interface{}
	// Label of argument
	Label string
	// Name of argument
	Name string
}

Argument struct

func (Argument) GetBool added in v0.3.1

func (a Argument) GetBool() bool

GetBool Get bool value of argument

func (Argument) GetInt added in v0.1.3

func (a Argument) GetInt() int64

GetInt Get int value of argument

func (Argument) GetString added in v0.1.3

func (a Argument) GetString() string

GetString Get string value of argument

func (Argument) GetUnit added in v0.3.1

func (a Argument) GetUnit() uint64

GetUnit Get int value of argument

type Arguments

type Arguments map[string]Argument

Arguments Console app arguments

type Command added in v0.4.0

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

Command is an argument list

func ParseCommand added in v0.4.0

func ParseCommand(command []byte) *Command

ParseCommand Parse command

func (*Command) Arguments added in v0.4.0

func (c *Command) Arguments() []Argument

Arguments command arguments

func (*Command) BindConnection added in v0.4.0

func (c *Command) BindConnection(conn net.Conn)

BindConnection Bind connection to command

func (*Command) GetOrigin added in v0.4.0

func (c *Command) GetOrigin() string

GetOrigin Get origin command

func (*Command) Response added in v0.8.2

func (c *Command) Response(result []byte) porterr.IError

Response Flat result of command to connection

func (*Command) Result added in v0.4.0

func (c *Command) Result(result []byte) porterr.IError

Result of command to connection

func (*Command) String added in v0.4.1

func (c *Command) String() string

Render command

func (*Command) UnbindConnection added in v0.4.0

func (c *Command) UnbindConnection()

UnbindConnection UnBind connection

type DNApp

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

DNApp Dynamic Name Application Implements Application interface

func (*DNApp) AttentionMessage added in v0.6.0

func (a *DNApp) AttentionMessage(message string, command ...*Command)

AttentionMessage printing attention message

func (*DNApp) FailMessage added in v0.6.0

func (a *DNApp) FailMessage(message string, command ...*Command)

FailMessage printing fail message

func (*DNApp) FatalError

func (a *DNApp) FatalError(err error)

FatalError Fatal error

func (*DNApp) GetAbsolutePath added in v0.5.0

func (a *DNApp) GetAbsolutePath(path string, dir string) (string, porterr.IError)

GetAbsolutePath Get absolute path to application

func (*DNApp) GetConfig

func (a *DNApp) GetConfig() interface{}

GetConfig Get config struct

func (*DNApp) GetConfigPath

func (a *DNApp) GetConfigPath(env string) string

GetConfigPath Get full path to config

func (*DNApp) GetLogger

func (a *DNApp) GetLogger() Logger

GetLogger Get logger

func (*DNApp) ParseConfig added in v0.5.0

func (a *DNApp) ParseConfig(env string) Application

ParseConfig parse config depends on env

func (*DNApp) ParseFlags

func (a *DNApp) ParseFlags(args *Arguments)

ParseFlags parse console arguments

func (*DNApp) SetConfig

func (a *DNApp) SetConfig(cfg interface{}) Application

SetConfig Set config struct

func (*DNApp) SetLogger added in v0.9.0

func (a *DNApp) SetLogger(logger Logger)

SetLogger Set logger

func (*DNApp) Start

func (a *DNApp) Start(address string, callback func(command *Command)) porterr.IError

Start run application

func (*DNApp) SuccessMessage added in v0.6.0

func (a *DNApp) SuccessMessage(message string, command ...*Command)

SuccessMessage printing success message

type Logger added in v0.0.7

type Logger interface {
	Output(callDepth int, message string) error

	Print(v ...interface{})
	Println(v ...interface{})
	Printf(format string, v ...interface{})

	Info(v ...interface{})
	Infoln(v ...interface{})
	Infof(format string, v ...interface{})

	Warn(v ...interface{})
	Warnln(v ...interface{})
	Warnf(format string, v ...interface{})

	Error(v ...interface{})
	Errorln(v ...interface{})
	Errorf(format string, v ...interface{})
}

Logger Common logger interface

func NewLogger

func NewLogger(config LoggerConfig) Logger

NewLogger Init logger struct

type LoggerConfig added in v0.9.0

type LoggerConfig struct {
	// Level of log message
	Level int
	// Default is 2
	Depth int
	// Flags
	Flags int
	// Format for multiple arguments
	Format LoggerFormat
}

LoggerConfig configuration of logger

type LoggerFormat added in v0.9.0

type LoggerFormat map[string]string

LoggerFormat logger prefix

func (LoggerFormat) FromContext added in v0.9.0

func (lf LoggerFormat) FromContext(ctx context.Context) string

FromContext create log prefix from context

func (LoggerFormat) String added in v0.9.0

func (lf LoggerFormat) String() string

String serialize format to string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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