shell

package
v1.4.4 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2023 License: MIT Imports: 33 Imported by: 5

Documentation

Overview

//////////////////////////////////////////////////////////////////// Manage global data, options, and common access functions

globalStore -- map of global variables and data structures

The globalStore is used to hold variables for the set command to manage and the command parser can leverage for variable substitution. The globalStore can store any object type as an interface{} enabling other functions to support more advanced variables.

Variable naming has some best practices to help segragate variables. Most best practices use a prefix in the variable name to signify specific use cases or variable types. For example:

"_" prefix for containing default information or immutable
    behavior (though immutable behavior is not enforced)
"$" prefix indicates a variable may be considered temporary. There
    are commands to delete all variables starting with $.
"." prefix indicates a variable may be considered configuration
"#" prefix for non-string variables (e.g. BSON document)

////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////// This package makes a good starting point

REM is actually executed internally in the processor as it does not work on parsed line (for now) ///////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////

Substitution functions

Registered substation functions can be used in variable substitution to
calculate values, provide variable formatting or generate unique data
values. Substitution functions have the ability to key any function call
so the same value can be returned in a subsequent call. A different key or
absence of key can result in a different value.

For example, a substitution function can generate a unique ID to be used
in a variable or HTTP body. Using a key allows the same guid to be substituted
multiple times. Without a key, a function is assumed to return a different
value but that is not guaranteed (for example a gettime() called repeatedly
may return the same time due to speed of the CPU)

A package init function can register functions using RegisterSubstitutionHandler. The
function registered identifies a function name and function group. The function
name is used in the substitution process to identify the function to call. The
functions group membership identifies the cached data used to manage key'ed
instance of function data. Multiple functions in the same group can use the
same cache data to ensure consistency for a given key.

A function is defined as: %%funcname([key, [fmt, [option]]])%%
When a function is parsed, the funcname is used to identify a function to
call. The function is given any previous data returned from a function
within a group (a group shares one cache item). Groups allow multiple data elements
to be associated together and accessed through a single key. For example:

A function group may manage the generation and display of a random mailing address.
When any function in the group is called, it would generate a random mailing address
if one was not previously generated. When the function returns the value for substitution
it also returns the raw data used to generate it so the substitution package can
maintain that state with a key. When any other function in the group is called with
the same key, it will get the raw data provided.

There is a newguid() function included in the system to serve as an example.

Index

Constants

View Source
const (
	CmdHelp int = iota
	CmdDebug
	CmdNetDebug
	CmdVerbose
	CmdTimeout
	CmdSilent
	CmdUrl
	CmdNoAuth
	CmdBasicAuth
	CmdQueryParamAuth
	CmdBenchmarks
	CmdRestclient
	CmdNoRedirect         // Encapsulated in CmdRestclient
	CmdSkipCertValidation // Encapsulated in CmdRestclient
	CmdFormatOutput
)

Options to include with a command

View Source
const (
	OptionDefaultTimeout              = 30000 // In milliseconds
	OptionDefaultUrl                  = ""
	OptionDefaultIterations           = 0
	OptionDefaultDuration             = ""
	OptionDefaultConcurrency          = 1
	OptionDefaultIterationsThrottleMs = 0
	OptionDefaultBasicAuth            = "[user][,pwd]"
	OptionDefaultQueryParamAuth       = "[[name,value]...]"
	OptionDefaultOutputFile           = ""
)

Default values for options

Variables

View Source
var (
	CategoryHttp        = "Http"
	CategorySpecialized = "Specialized"
	CategoryUtilities   = "Utility"
	CategoryBenchmarks  = "Benchmark"
	CategoryTests       = "Test"
	CategoryAnalysis    = "Result Processing"
	CategoryHelp        = "Help"
)

Variables for supported categorizations of commands

View Source
var (
	ErrArguments         = errors.New("Invalid arguments")
	ErrInvalidValue      = errors.New("Invalid value type")
	ErrNotFound          = errors.New("Node not found")
	ErrInvalidPath       = errors.New("Node path error")
	ErrInvalidKey        = errors.New("Invalid key")
	ErrUnexpectedType    = errors.New("Node is unexpected type")
	ErrDataType          = errors.New("Invalid history data type")
	ErrNoHistory         = errors.New("History not present")
	ErrArrayOutOfBounds  = errors.New("Array index out of bounds")
	ErrInvalidSubCommand = errors.New("Invalid sub-command")
	ErrNotImplemented    = errors.New("Command not implemented")
)

Error variables

View Source
var (
	DefaultInitFileName  = ".rsconfig"
	DefaultInitFileExt   = ".user"
	DefaultScriptFileExt = ".rshell"
	ProgramName          = "RestShell"
	ProgramArgs          = make([]string, 0)
)

Default settings for startup

View Source
var AnonymousAuth = NoAuth{}
View Source
var DefaultScriptExtension = ".rshell"
View Source
var ExecutableDirectory string = ""
View Source
var InitDirectory string = ""
View Source
var LastError int = 0

Functions

func AddAboutTopic added in v1.4.2

func AddAboutTopic(topic TopicInterface)

func AddAlias

func AddAlias(key string, command string, force bool) error

AddAlias - Add an aliased command to the library

func AddCommand

func AddCommand(name string, category string, cmd Command)

AddCommand -- Add a command to registry Cmd structures should avoid pointers to data structures so cmd structures can be duplicated into separate instances without data collision

func AddCommonCmdOptions

func AddCommonCmdOptions(set CmdSet, options ...int)

AddCommonCmdOptions -- Add the given command options to the options supported by the current executing command

func ClearCmdOptions

func ClearCmdOptions()

ClearCmdOptions -- Clear common command options by setting a new configuration.

func CmdParse

func CmdParse(set CmdSet, tokens []string) error

CmdParse -- implements the parse/getopt function by hiding an Option type not to be exported in the interface

func ColumnizeTokens

func ColumnizeTokens(tokens []string, columns int, width int) []string

func CommandProcessesLine

func CommandProcessesLine(cmd interface{}) bool

func CommandProcessor

func CommandProcessor(defaultPrompt string, reader io.Reader, singleStep bool, allowAbort bool) (int, bool)

CommandProcessor -- Start the command interpretter using the given reader and options and return the number of commands executed and whether it completed successfully

func ConsoleWriter

func ConsoleWriter() io.Writer

Output that is intended only for the console; typically help information and general shell/command processor debug

func ContainsCommand

func ContainsCommand(cmd string, tokens []string) bool

func ConvertNodeValueToString added in v1.3.0

func ConvertNodeValueToString(node interface{}) (string, error)

ConvertNodeValueTostring -- convert a node result to a string value

func Delay

func Delay(value time.Duration)

Delay - Non-abortable delay function

func DisplayCmdHelp

func DisplayCmdHelp(set *getopt.Set, cmd string)

func DisplayHelp

func DisplayHelp()

func DoesCommandRequestNoStep added in v1.4.4

func DoesCommandRequestNoStep(cmd interface{}) bool

func DoesCommandRequestQuit added in v1.4.4

func DoesCommandRequestQuit(cmd interface{}) bool

func EnableGlobalOptions

func EnableGlobalOptions()

func EnumerateGlobals

func EnumerateGlobals(fn func(key string, value interface{}), filter func(string, interface{}) bool)

func ErrorWriter

func ErrorWriter() io.Writer

General output that goes to the console stderr and a log file

func EscapeStringValue added in v1.4.0

func EscapeStringValue(input string) string

EscapeStringValue -- Quote a string handling '\"' as well

func ExpandAlias added in v1.3.0

func ExpandAlias(command string) (string, error)

ExpandAlias - Expand alias in input string

func FormBodyValidate

func FormBodyValidate(debug bool, body string)

FormBodyValidate - Validate form data is ok; only display a warning if not

func FormatMsTime

func FormatMsTime(v float64) string

func GetAlias

func GetAlias(key string) (string, error)

GetAlias - get the alias command from the library

func GetAllAliasKeys

func GetAllAliasKeys() []string

GetAllAliasKeys -- gets a list of keys from the library

func GetBinaryFileContents

func GetBinaryFileContents(filename string) ([]byte, error)

func GetCmdConcurrencyValue

func GetCmdConcurrencyValue() int

func GetCmdDurationValueWithFallback added in v1.3.0

func GetCmdDurationValueWithFallback(d time.Duration) time.Duration

func GetCmdHeaderValues

func GetCmdHeaderValues() []string

func GetCmdIterationThrottleMs

func GetCmdIterationThrottleMs() int

func GetCmdIterationValue

func GetCmdIterationValue() int

func GetCmdOutputFileName

func GetCmdOutputFileName() string

func GetCmdTimeoutValueMs

func GetCmdTimeoutValueMs() int64

func GetCmdUrlValue

func GetCmdUrlValue(fallback string) (result string)

func GetExeDirectory

func GetExeDirectory() string

func GetFileContents

func GetFileContents(filename string) (string, error)

func GetFileContentsOfType

func GetFileContentsOfType(file string, extension string) (string, error)

GetFileContentsOfType -- read the file contents using a default extension if one was not provided

func GetGlobal

func GetGlobal(key string) interface{}

func GetGlobalString

func GetGlobalString(key string) string

func GetGlobalStringWithFallback

func GetGlobalStringWithFallback(key string, fallback string) string

func GetInitDirectory

func GetInitDirectory() string

func GetLine

func GetLine(prompt string) string

func GetPassword

func GetPassword(prompt string) string

func GetValidatedFileName

func GetValidatedFileName(file string, extension string) (string, error)

Validate a file exists in full format or with expected extension added. Return the file that was verified that exists or an error. Note: extension must be all lower case

func GetValueAsDate

func GetValueAsDate(i interface{}) (time.Time, error)

GetValueAsDate -- given a scaler value in an interface convert it to a date if it is can be converted

func GetX509Pool

func GetX509Pool() *x509.CertPool

GetX509Pool - Get the X509 pool to use; the system is used by default and a cert.pem file is appended if it can be found in the init directory, or the exe directory.

func InitializeCommonCmdOptions

func InitializeCommonCmdOptions(set CmdSet, options ...int)

InitializeCommonCmdOptions initialize common command options

func InitializeGlobal

func InitializeGlobal(key string, value interface{}) error

Only set the global if not initialized already

func InitializeShell

func InitializeShell()

InitializeShell -- Initialize common parameters needed by the shell

func IsBody

func IsBody(l []DisplayOption) bool

func IsCmdBasicAuthEnabled

func IsCmdBasicAuthEnabled() bool

func IsCmdCsvFormatEnabled

func IsCmdCsvFormatEnabled() bool

func IsCmdDebugEnabled

func IsCmdDebugEnabled() bool

func IsCmdFormattedCsvEnabled

func IsCmdFormattedCsvEnabled() bool

func IsCmdFullOutputEnabled

func IsCmdFullOutputEnabled() bool

func IsCmdHeaderDisabled

func IsCmdHeaderDisabled() bool

func IsCmdHelpEnabled

func IsCmdHelpEnabled() bool

func IsCmdLocalCertsEnabled

func IsCmdLocalCertsEnabled() bool

func IsCmdNetDebugEnabled

func IsCmdNetDebugEnabled() bool

func IsCmdNoAuthEnabled

func IsCmdNoAuthEnabled() bool

func IsCmdNoRedirectEnabled

func IsCmdNoRedirectEnabled() bool

func IsCmdOutputBodyEnabled

func IsCmdOutputBodyEnabled() bool

func IsCmdOutputCookieEnabled

func IsCmdOutputCookieEnabled() bool

func IsCmdOutputHeaderEnabled

func IsCmdOutputHeaderEnabled() bool

func IsCmdOutputRequestEnabled added in v1.3.0

func IsCmdOutputRequestEnabled() bool

func IsCmdOutputShortEnabled

func IsCmdOutputShortEnabled() bool

func IsCmdPrettyPrintEnabled

func IsCmdPrettyPrintEnabled() bool

func IsCmdQueryParamAuthEnabled

func IsCmdQueryParamAuthEnabled() bool

func IsCmdReconnectEnabled

func IsCmdReconnectEnabled() bool

func IsCmdSilentEnabled

func IsCmdSilentEnabled() bool

func IsCmdSkipCertValidationEnabled

func IsCmdSkipCertValidationEnabled() bool

func IsCmdVerboseEnabled

func IsCmdVerboseEnabled() bool

func IsCmdWarmingEnabled

func IsCmdWarmingEnabled() bool

func IsCookies

func IsCookies(l []DisplayOption) bool

func IsDebugEnabled

func IsDebugEnabled() bool

func IsDisplayHelpEnabled

func IsDisplayHelpEnabled() bool

func IsFlowControl

func IsFlowControl(err error, action FlowErrorCmd) bool

IsFlowControl - Determines if the error as the given action associated

func IsHeaders

func IsHeaders(l []DisplayOption) bool

func IsNetDebugEnabled

func IsNetDebugEnabled() bool

func IsPrettyPrint

func IsPrettyPrint(l []DisplayOption) bool

func IsShort

func IsShort(l []DisplayOption) bool

func IsSilentEnabled

func IsSilentEnabled() bool

func IsStatus

func IsStatus(l []DisplayOption) bool

func IsStringBinary

func IsStringBinary(text string) bool

func IsValidKey

func IsValidKey(key string) bool

func IsVariableSubstitutionComplete

func IsVariableSubstitutionComplete(input string) bool

IsVariableSubstitutionComplete -- Validate that variable substitution was complete (no variable syntax found)

func IsVerboseEnabled

func IsVerboseEnabled() bool

func JsonBodyValidate

func JsonBodyValidate(debug bool, body string)

JsonBodyValidate - Validate form data is ok; only display a warning if not

func JsonCompletionHandler

func JsonCompletionHandler(json string, resperr error, shortDisplay ShortDisplayFunc) error

JsonCompletionHandler -- Helper function to push json result data and perform output processing

func LineParse

func LineParse(input string) []string

LineParse -- Parse a command line into tokens handling escape sequences and double quotes

func MessageCompletionHandler added in v1.3.0

func MessageCompletionHandler(str string, resperr error) error

MessageCompletionHandler -- Helper function to push plain text result and perform output processing

func NewFlowError

func NewFlowError(msg string, cmd FlowErrorCmd) error

NewFlowError - Return a FlowError which provides actions to cmd processor

func OnVerbose

func OnVerbose(format string, a ...interface{})

func OpenFileForOutput

func OpenFileForOutput(name string, truncate bool, append bool, newfile bool) (*os.File, error)

OpenFileForOutput -- open a file

func OutputResult

func OutputResult(result Result, shortDisplay ShortDisplayFunc) (resperr error)

func OutputWriter

func OutputWriter() io.Writer

General output that can go to the console stdout or to a log File Generally this is data, verbose output, and debug related to a function

func ParseDuration

func ParseDuration(timeArg string, suffix ...string) (time.Duration, error)

ParseDuration -- parses a duration value from text that may include time sufix [ms(default), S, see time.ParseDuration]

func PerformHealthCheck

func PerformHealthCheck(client RestClient, url string) error

PerformHealthCheck - Valiate a default /health endpoint TODO: Evaluate moving this to specialized commands; it is not generic enough to be here

func PerformVariableSubstitution

func PerformVariableSubstitution(input string) string

PerformVariableSubstitution -- perform substitution on a string

func ProcessJob

func ProcessJob(options JobOptions, jm JobMonitor)

ProcessJob -- Run the jobs based on provided options

func PushError

func PushError(resperror error) error

PushError - push a result that is a single string with the error message

func PushResponse

func PushResponse(resp *RestResponse, resperror error) error

PushResponse -- Push a RestResponse into the history buffer

func PushResult

func PushResult(result Result) error

PushResult -- push a Result structure into the history buffer

func PushText

func PushText(contentType string, data string, resperror error) error

PushResponse -- Push a RestResponse into the history buffer

func ReadLine

func ReadLine()

ReadLine -- reads a line from standard in if it is a terminal

func RegisterSubstitutionHandler

func RegisterSubstitutionHandler(function SubstitutionFunction)

RegisterSubstitutionHandler -- Register a substitution function

func RemoveAlias

func RemoveAlias(key string) error

RemoveAlias - remove an alias from the library

func RemoveGlobal

func RemoveGlobal(key string)

func ResetOutput

func ResetOutput() (io.Writer, error)

func RestCompletionHandler

func RestCompletionHandler(response *RestResponse, resperr error, shortDisplay ShortDisplayFunc) error

RestCompletionHandler -- Helper function to push rest result and perform output processing

func RunShell

func RunShell(options StartupOptions) (exitCode int)

RunShell -- process command line and init scripts and run command processor

func SetAuthContext

func SetAuthContext(ctx string, auth Auth)

func SetDebug

func SetDebug(val bool)

func SetGlobal

func SetGlobal(key string, value interface{}) error

func SetOutput

func SetOutput(o io.Writer) error

func SetSilent

func SetSilent(val bool)

func SetVerbose

func SetVerbose(val bool)

func SortedMapKeys

func SortedMapKeys(mapData map[string]interface{}) []string

SortedMapKeys -- Sort a list of keys for a map

func SortedStringSlice

func SortedStringSlice(commands []string) []string

SortedStringSlice -- sort a slice of strings

func SubstitutionFunctionNames

func SubstitutionFunctionNames() []string

SubstitutionFunctionNames -- return the list of substitute functions by name in sorted order

func TryGetGlobalString

func TryGetGlobalString(key string) (string, bool)

func ValidateScriptExists

func ValidateScriptExists(file string) (string, error)

ValidateScriptExists -- Validate the script exists by either basename or basename plus suffix return the file name modified with extension if necesssary. If the error is not a file existence problem the file is returned.

func XmlBodyValidate

func XmlBodyValidate(debug bool, body string)

XmlBodyValidate - Validate form data is ok; only display a warning if not

Types

type Abortable

type Abortable interface {
	Abort()
}

Abortable - interface for commands that support abort

type Auth

type Auth interface {
	IsAuthed() bool
	AddAuth(*http.Request)
	ToString() string
}

func GetAuthContext

func GetAuthContext(ctx string) (Auth, error)

func GetCmdBasicAuthContext

func GetCmdBasicAuthContext(fallback Auth) Auth

func GetCmdQueryParamAuthContext

func GetCmdQueryParamAuthContext(fallback Auth) Auth

type BasicAuth

type BasicAuth struct {
	UserName string
	Password string
}

func NewBasicAuth

func NewBasicAuth(u string, p string) BasicAuth

func (BasicAuth) AddAuth

func (a BasicAuth) AddAuth(req *http.Request)

func (BasicAuth) IsAuthed

func (a BasicAuth) IsAuthed() bool

func (BasicAuth) ToString

func (a BasicAuth) ToString() string

type Benchmark

type Benchmark struct {
	Iterations []BenchmarkIteration
	StartTime  time.Time
	Duration   time.Duration
	Note       string
	// contains filtered or unexported fields
}

Benchmark -- Structure implementing JobMontor

func NewBenchmark

func NewBenchmark(iterations int) *Benchmark

func (*Benchmark) AddIterationMessage

func (bm *Benchmark) AddIterationMessage(i int, msg string)

func (*Benchmark) Dump

func (bm *Benchmark) Dump(label string, opts StandardOptions, showIterations bool)

func (*Benchmark) DumpIterations

func (bm *Benchmark) DumpIterations(opts StandardOptions)

func (*Benchmark) End

func (bm *Benchmark) End()

func (*Benchmark) FinalizeIteration added in v1.3.0

func (bm *Benchmark) FinalizeIteration(jc JobContext)

func (*Benchmark) HighTimeFmt

func (bm *Benchmark) HighTimeFmt() string

func (*Benchmark) HighTimeInMs

func (bm *Benchmark) HighTimeInMs() float64

func (*Benchmark) HlAverageFmt

func (bm *Benchmark) HlAverageFmt() string

func (*Benchmark) HlAverageInMs

func (bm *Benchmark) HlAverageInMs() float64

func (*Benchmark) LowTimeFmt

func (bm *Benchmark) LowTimeFmt() string

func (*Benchmark) LowTimeInMs

func (bm *Benchmark) LowTimeInMs() float64

func (*Benchmark) Start

func (bm *Benchmark) Start()

func (*Benchmark) StartIteration

func (bm *Benchmark) StartIteration(i int) JobContext

func (*Benchmark) WallAverageFmt

func (bm *Benchmark) WallAverageFmt() string

func (*Benchmark) WallAverageInMs

func (bm *Benchmark) WallAverageInMs() float64

func (*Benchmark) WallTimeFmt

func (bm *Benchmark) WallTimeFmt() string

func (*Benchmark) WallTimeInMs

func (bm *Benchmark) WallTimeInMs() float64

type BenchmarkIteration

type BenchmarkIteration struct {
	Iteration int
	WallTime  int64 // Nano-seconds
	Err       error
	Messages  []string
	Custom    interface{}
	// contains filtered or unexported fields
}

BenchmarkIteration -- Iteration structure implementing JobContext

func (*BenchmarkIteration) DumpLine

func (bi *BenchmarkIteration) DumpLine(opts StandardOptions, displayFmt string, start time.Time)

func (*BenchmarkIteration) EndIteration added in v1.3.0

func (jc *BenchmarkIteration) EndIteration(err error)

func (*BenchmarkIteration) UpdateError added in v1.3.0

func (jc *BenchmarkIteration) UpdateError(err error)

func (*BenchmarkIteration) WallTimeFmt

func (bi *BenchmarkIteration) WallTimeFmt() string

func (*BenchmarkIteration) WallTimeInMs

func (bi *BenchmarkIteration) WallTimeInMs() float64

type CmdSet

type CmdSet interface {
	Reset()
	Usage()
	SetProgram(string)
	SetParameters(string)
	SetUsage(func())
	PrintUsage(io.Writer)
	BoolLong(string, rune, ...string) *bool
	StringLong(string, rune, string, ...string) *string
	IntLong(string, rune, int, ...string) *int
	Int64Long(string, rune, int64, ...string) *int64
	StringListLong(string, rune, ...string) *StringList
	Args() []string
	Arg(int) string
	NArgs() int
}

CmdSet -- Interface exposing the supported interfaces to commands for setting options

func NewCmdSet

func NewCmdSet() CmdSet

NewCmdSet -- Create a command set for handling options

type Command

type Command interface {
	Execute([]string) error
	AddOptions(CmdSet)
}

Command - interface for basic command

type CommandWithSubcommands

type CommandWithSubcommands interface {
	GetSubCommands() []string
}

CommandWithSubcommands - interface for commands that have sub-commands

type CookieAuth

type CookieAuth struct {
	CookieName string
	AuthToken  string
}

type DisplayOption

type DisplayOption int

DisplayOption

const (
	Body DisplayOption = iota
	Headers
	Cookies
	Status
	Short
	Pretty
	All
)

DisplayOption values

func GetDefaultDisplayOptions

func GetDefaultDisplayOptions() []DisplayOption

type FlowControl

type FlowControl interface {
	RequestQuit() bool
	RequestNoStep() bool
}

FlowControl - Special Command interfaces to control execution within the command processor

type FlowError

type FlowError struct {
	Message string
	Cmd     FlowErrorCmd
}

func (FlowError) Error

func (f FlowError) Error() string

Error - Return the error message for a flow error

type FlowErrorCmd

type FlowErrorCmd string

FlowErrorCmd -- rename FlowAction - Special values affecting command processor

var (
	// FlowQuit - Terminate the current script without an error but do not clear LastError
	FlowQuit FlowErrorCmd = "q"
	// FlowAbort - Terminate the current script with error (typically Ctrl-C during command)
	FlowAbort FlowErrorCmd = "a"
	// FlowGo - Continue and exit single step mode
	FlowGo FlowErrorCmd = "g"
)

type HistoryMap

type HistoryMap interface {
	GetNode(string) (interface{}, error)
}

func NewJsonHistoryMap

func NewJsonHistoryMap(data string) (HistoryMap, error)

NewJsonHistoryMap -- Create a HistoryMap from json string content

func NewSimpleHistoryMap

func NewSimpleHistoryMap(m map[string]string) (HistoryMap, error)

func NewTextHistoryMap

func NewTextHistoryMap(text string) (HistoryMap, error)

func NewXmlHistoryMap

func NewXmlHistoryMap(data string) (HistoryMap, error)

type HistoryOptions

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

HistoryOptions -- Common options for history results

func AddHistoryOptions

func AddHistoryOptions(set CmdSet, payloadType ...ResultPayloadType) HistoryOptions

AddHistoryOptions -- Add options for history payload types

func (*HistoryOptions) ClearPathOptions

func (ho *HistoryOptions) ClearPathOptions()

func (HistoryOptions) GetNode

func (ho HistoryOptions) GetNode(path string, result Result) (interface{}, error)

func (HistoryOptions) GetNodeFromHistory added in v1.3.0

func (ho HistoryOptions) GetNodeFromHistory(index int, path string) (interface{}, error)

func (HistoryOptions) IsAuthPath

func (ho HistoryOptions) IsAuthPath() bool

IsAuthPath -- Is the Authenticadtion token path option selected to parse JWT

func (HistoryOptions) IsCookiePath

func (ho HistoryOptions) IsCookiePath() bool

IsCookiePath -- Is the cookie path option selected to extract cookie

func (HistoryOptions) IsHeaderPath

func (ho HistoryOptions) IsHeaderPath() bool

IsHeaderPath -- Is the history path option selected

func (HistoryOptions) IsHistoryPathOptionEnabled

func (ho HistoryOptions) IsHistoryPathOptionEnabled() bool

IsPathOptionEnabled -- True if any history path option is enabled

func (HistoryOptions) IsHttpStatusPath

func (ho HistoryOptions) IsHttpStatusPath() bool

IsHeaderPath -- Is the history path option selected

func (HistoryOptions) IsResultPathOption

func (ho HistoryOptions) IsResultPathOption() bool

IsPathOption -- Is the history path option selected

func (*HistoryOptions) SetPathOption

func (ho *HistoryOptions) SetPathOption(payloadType ResultPayloadType)

type JobCompletion

type JobCompletion func(job int, jc JobContext, resp *RestResponse)

JobCompletion -- Function prototype for a function that can parse the response

func MakeJobCompletionForExpectedStatus

func MakeJobCompletionForExpectedStatus(status int) JobCompletion

MakeJobCompletionForExpectedStatus -- Create a completion handler to accept a different status than StatusOK

type JobContext added in v1.3.0

type JobContext interface {
	EndIteration(error)
	UpdateError(error)
}

JobContext is returned by the start of an iteration to collect iteration information for the completed iteration

type JobFunction

type JobFunction func() (*RestResponse, error)

JobFunction -- Function prototype for a function that will perform an instance of the job

type JobMaker

type JobMaker func() JobFunction

JobMaker -- Function prototype for a function that can create an instance of the job function

type JobMonitor

type JobMonitor interface {
	Start()
	StartIteration(int) JobContext
	FinalizeIteration(JobContext)
	End()
}

JobMonitor -- interface to support benchmark capabilities

type JobOptions

type JobOptions struct {
	Concurrency       int
	Iterations        int
	Duration          time.Duration
	ThrottleInMs      int
	EnableWarming     bool
	JobMaker          JobMaker
	CompletionHandler JobCompletion
	CancelPtr         *bool
}

JobOptions -- options available to the job processing engine

func GetJobOptionsFromParams

func GetJobOptionsFromParams() JobOptions

GetJobOptionsFromParams -- initializes options from common command line options

type JsonMap added in v1.3.0

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

JsonMap -- contains a deserialized json

func (*JsonMap) GetJsonObject added in v1.3.0

func (jm *JsonMap) GetJsonObject() (map[string]interface{}, error)

func (*JsonMap) GetNode added in v1.3.0

func (jm *JsonMap) GetNode(path string) (interface{}, error)

GetNode -- Get a JSON node from a map structure mapped from a json object or array

type JwtHeaderAuth

type JwtHeaderAuth struct {
	AuthToken string
}

func NewJwtHeaderAuth

func NewJwtHeaderAuth(t string) JwtHeaderAuth

func (JwtHeaderAuth) AddAuth

func (a JwtHeaderAuth) AddAuth(req *http.Request)

func (JwtHeaderAuth) IsAuthed

func (a JwtHeaderAuth) IsAuthed() bool

func (JwtHeaderAuth) ToString

func (a JwtHeaderAuth) ToString() string

type Line

type Line struct {
	OriginalLine string
	CmdLine      string
	Echo         bool
	Step         bool
	NoSubstitute bool
	IsComment    bool
	Command      string
	ArgString    string
}

Line -- a structure for a parsed line

func NewCommandLine

func NewCommandLine(input string, shellPrefix string) (line *Line, reterr error)

NewCommandLine -- parse command line into a Line

func (*Line) GetCmdAndArguments

func (line *Line) GetCmdAndArguments() []string

GetCmdAndArguments -- get the tokens of the commmand line fully parsed (obsolete)

func (*Line) GetTokens added in v1.4.4

func (line *Line) GetTokens() []string

GetTokens -- get the line tokens

type LineProcessor

type LineProcessor interface {
	ExecuteLine(line string, echoed bool) error
}

LineProcessor - interface for commands that execute whole line

type NoAuth

type NoAuth struct {
}

func (NoAuth) AddAuth

func (a NoAuth) AddAuth(req *http.Request)

func (NoAuth) IsAuthed

func (a NoAuth) IsAuthed() bool

func (NoAuth) ToString

func (a NoAuth) ToString() string

type QueryParamAuth

type QueryParamAuth struct {
	KeyPairs []QueryParmKeyValue
}

func NewQueryParamAuth

func NewQueryParamAuth(kv ...string) QueryParamAuth

func (QueryParamAuth) AddAuth

func (a QueryParamAuth) AddAuth(req *http.Request)

func (QueryParamAuth) GetKeyValue

func (a QueryParamAuth) GetKeyValue(key string) (string, bool)

func (QueryParamAuth) IsAuthed

func (a QueryParamAuth) IsAuthed() bool

func (QueryParamAuth) ToString

func (a QueryParamAuth) ToString() string

type QueryParmKeyValue

type QueryParmKeyValue struct {
	Key   string
	Value string
}

type RemCommand

type RemCommand struct {
}

func NewRemCommand

func NewRemCommand() *RemCommand

func (*RemCommand) AddOptions

func (cmd *RemCommand) AddOptions(set CmdSet)

func (*RemCommand) CommandCount

func (cmd *RemCommand) CommandCount() int

func (*RemCommand) DoNotClearError

func (cmd *RemCommand) DoNotClearError() bool

func (*RemCommand) DoNotCount

func (cmd *RemCommand) DoNotCount() bool

func (*RemCommand) Execute

func (cmd *RemCommand) Execute(args []string) error

func (*RemCommand) ExecuteLine

func (cmd *RemCommand) ExecuteLine(line string, echoed bool) error

func (*RemCommand) RequestNoStep

func (cmd *RemCommand) RequestNoStep() bool

func (*RemCommand) RequestQuit

func (cmd *RemCommand) RequestQuit() bool

type RestClient

type RestClient struct {
	Debug         bool
	Verbose       bool
	OutputRequest bool
	Headers       []string
	Client        *http.Client
}

RestClient -- An object that makes REST calls

func NewRestClient

func NewRestClient() RestClient

func NewRestClientFromOptions

func NewRestClientFromOptions() RestClient

func (*RestClient) DisableCertValidation

func (r *RestClient) DisableCertValidation()

DisableCertValidation -- A function to disable cert validation in the rest client TODO: cleanup relationship be between skipping verification and including certificates

func (*RestClient) DisableRedirect

func (r *RestClient) DisableRedirect()

func (*RestClient) DoGet

func (r *RestClient) DoGet(authContext Auth, url string) (resultResponse *RestResponse, resultError error)

func (*RestClient) DoMethod

func (r *RestClient) DoMethod(method string, authContext Auth, url string) (resultResponse *RestResponse, resultError error)

func (*RestClient) DoMethodWithBody

func (r *RestClient) DoMethodWithBody(method string, authContext Auth, url string, contentType string, data string) (resultResponse *RestResponse, resultError error)

DoMethodWithBody - Perform a HTTP request for the given method type and content provided

func (*RestClient) DoWithForm

func (r *RestClient) DoWithForm(method string, authContext Auth, url string, data string) (resultResponse *RestResponse, resultError error)

func (*RestClient) DoWithJson

func (r *RestClient) DoWithJson(method string, authContext Auth, url string, data string) (resultResponse *RestResponse, resultError error)

func (*RestClient) DoWithJsonMarshal

func (r *RestClient) DoWithJsonMarshal(method string, authContext Auth, url string, data interface{}) (*RestResponse, error)

func (*RestClient) DoWithXml

func (r *RestClient) DoWithXml(method string, authContext Auth, url string, data string) (resultResponse *RestResponse, resultError error)

DoWithXml -- Perform an HTTP method request with an XML body

func (*RestClient) EnableRedirect

func (r *RestClient) EnableRedirect()

type RestResponse

type RestResponse struct {
	Text string
	// contains filtered or unexported fields
}

RestResponse -- The response structure returned by a REST interface

func (*RestResponse) GetContentType

func (resp *RestResponse) GetContentType() string

func (*RestResponse) GetCookies

func (resp *RestResponse) GetCookies() []*http.Cookie

func (*RestResponse) GetHeader

func (resp *RestResponse) GetHeader() http.Header

func (*RestResponse) GetStatus

func (resp *RestResponse) GetStatus() int

GetStatus - Get the status return code in the response; if the response is invalid or not initialized it will return -1

func (*RestResponse) GetStatusString

func (resp *RestResponse) GetStatusString() string

GetStatusString - Get the status code in string format for the response; if the response is invalid or not initialized it will return "Unknown Status".

type Result

type Result struct {
	Text             string
	Error            error
	HttpStatus       int
	HttpStatusString string
	ContentType      string
	BodyMap          HistoryMap
	HeaderMap        HistoryMap
	CookieMap        HistoryMap
	AuthMap          HistoryMap
	// contains filtered or unexported fields
}

Result -- a result that can be placed in the history buffer and used by assertion handlers

func NewJSONResult added in v1.4.1

func NewJSONResult(text string) *Result

func NewTextResult added in v1.4.1

func NewTextResult(text string) *Result

func PeekResult

func PeekResult(index int) (Result, error)

PeekResult - Get a history result using an index. Index from the end of the array which was the last item appended

func (*Result) DumpCookies

func (r *Result) DumpCookies(w io.Writer)

func (*Result) DumpHeader

func (r *Result) DumpHeader(w io.Writer)

func (*Result) DumpResult

func (r *Result) DumpResult(w io.Writer, options ...DisplayOption)

type ResultContentType

type ResultContentType string

ResultContentType -- types of result data

var (
	ResultContentUnknown ResultContentType = "unknown"
	ResultContentXml     ResultContentType = "xml"
	ResultContentJson    ResultContentType = "json"
	ResultContentText    ResultContentType = "text"
	ResultContentHtml    ResultContentType = "html"
	ResultContentCsv     ResultContentType = "csv"
	ResultContentForm    ResultContentType = "form"
	ResultContentBinary  ResultContentType = "binary"
)

type ResultPayloadType

type ResultPayloadType int
const (
	ResultPath     ResultPayloadType = 1
	AuthPath       ResultPayloadType = 2
	CookiePath     ResultPayloadType = 3
	HeaderPath     ResultPayloadType = 4
	AllPaths       ResultPayloadType = 8
	AlternatePaths ResultPayloadType = 9 // All paths but default as default is assumed
)

Path options scenarios for different use cases

type RunCommand

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

RunCommand - The run command structure Note: Run is a command that recurses, so values here can be changed by nested RUNs. Use local variables for data to be preserved.

func NewRunCommand

func NewRunCommand() *RunCommand

func (*RunCommand) Abort

func (cmd *RunCommand) Abort()

func (*RunCommand) AddOptions

func (cmd *RunCommand) AddOptions(set CmdSet)

func (*RunCommand) CommandCount

func (cmd *RunCommand) CommandCount() int

func (*RunCommand) DoNotClearError

func (cmd *RunCommand) DoNotClearError() bool

func (*RunCommand) DoNotCount

func (cmd *RunCommand) DoNotCount() bool

func (*RunCommand) Execute

func (cmd *RunCommand) Execute(args []string) error

type ShortDisplayFunc

type ShortDisplayFunc func(io.Writer, Result) error

ShortDisplayFunc -- A function can be used to pretty format the output or condense it

type SiegeBucket added in v1.3.0

type SiegeBucket struct {
	// Initialized data
	Label  string
	Period int
	End    time.Time

	// Updated data protected by mutex
	StartedJobs      int
	SuccessfulJobs   int
	SuccessDurations time.Duration
	FailedJobs       int
	FailedDurations  time.Duration
	TotalDuration    time.Duration
	// contains filtered or unexported fields
}

SiegeBucket -- structure for histogram of siege benchmark

type Siegemark added in v1.3.0

type Siegemark struct {
	StartTime      time.Time
	Duration       time.Duration
	BucketDuration time.Duration
	LateStarts     int
	Note           string

	Buckets []SiegeBucket
	// contains filtered or unexported fields
}

Siegemark -- JobMonitor for siege benchmarking

func NewSiegemark added in v1.3.0

func NewSiegemark(duration time.Duration, buckets int) *Siegemark

NewSiegemark -- Create siege benchmarking job monitor

func (*Siegemark) AddIterationMessage added in v1.3.0

func (sm *Siegemark) AddIterationMessage(i int, msg string)

func (*Siegemark) Dump added in v1.3.0

func (sm *Siegemark) Dump(label string, opts StandardOptions, showIterations bool)

Dump -- Dump to output stream the information formated as options requested

func (*Siegemark) DumpIterations added in v1.3.0

func (sm *Siegemark) DumpIterations(opts StandardOptions)

DumpIterations -- Dumps the iterations or with Siegemark the buckets

func (*Siegemark) End added in v1.3.0

func (sm *Siegemark) End()

End -- Record the End a benchmark

func (*Siegemark) FinalizeIteration added in v1.3.0

func (sm *Siegemark) FinalizeIteration(jc JobContext)

FinalizeIteration -- Fold iteration data into aggregated bucket data

func (*Siegemark) Start added in v1.3.0

func (sm *Siegemark) Start()

Start -- Start a benchmark

func (*Siegemark) StartIteration added in v1.3.0

func (sm *Siegemark) StartIteration(i int) JobContext

StartIteration -- Start an iteration

type SiegemarkIteration added in v1.3.0

type SiegemarkIteration struct {
	Iteration int
	StartTime time.Time
	EndTime   time.Time
	Error     error
}

SiegemarkIteration -- track a single rest call

func (*SiegemarkIteration) EndIteration added in v1.3.0

func (si *SiegemarkIteration) EndIteration(err error)

EndIteration -- Collect completion data on iteration

func (*SiegemarkIteration) UpdateError added in v1.3.0

func (si *SiegemarkIteration) UpdateError(err error)

UpdateError -- Update the error on an iteration

type StandardOptions

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

Structure for all common option values

func GetStdOptions

func GetStdOptions() StandardOptions

func (StandardOptions) Clear

func (o StandardOptions) Clear(options ...int) StandardOptions

Clear -- Return a copy of the standard options with the specified options set to false for booleans or otherwise default values

func (*StandardOptions) GetBasicAuthContext

func (o *StandardOptions) GetBasicAuthContext(fallback Auth) Auth

GetBasicAuthContext -- get the Auth context for the basic auth parameters specified

func (*StandardOptions) GetCmdConcurrencyValue

func (o *StandardOptions) GetCmdConcurrencyValue() int

func (*StandardOptions) GetCmdDurationValueWithFallback added in v1.3.0

func (o *StandardOptions) GetCmdDurationValueWithFallback(d time.Duration) time.Duration

GetCmdDurationValueWithFallback -- Get the duration parameter use default if not set

func (*StandardOptions) GetCmdIterationThrottleMs

func (o *StandardOptions) GetCmdIterationThrottleMs() int

func (*StandardOptions) GetCmdIterationValue

func (o *StandardOptions) GetCmdIterationValue() int

GetCmdIterationValue -- Get the iteration value and use the default if not set

func (*StandardOptions) GetCmdIterationValueWithFallback added in v1.3.0

func (o *StandardOptions) GetCmdIterationValueWithFallback(d int) int

GetCmdIterationValueWithFallback -- Get the iteration value and use the default if not set

func (*StandardOptions) GetCmdOutputFileName

func (o *StandardOptions) GetCmdOutputFileName() string

func (*StandardOptions) GetHeaderValues

func (o *StandardOptions) GetHeaderValues() []string

func (*StandardOptions) GetQueryParamAuthContext

func (o *StandardOptions) GetQueryParamAuthContext(fallback Auth) Auth

GetQueryParamAuthContext -- return the Auth context for query parameters specified in command

func (*StandardOptions) GetTimeoutValueMs

func (o *StandardOptions) GetTimeoutValueMs() int64

func (*StandardOptions) GetUrlValue

func (o *StandardOptions) GetUrlValue(fallback string) (result string)

func (*StandardOptions) IsBasicAuthEnabled

func (o *StandardOptions) IsBasicAuthEnabled() bool

func (*StandardOptions) IsCsvOutputEnabled

func (o *StandardOptions) IsCsvOutputEnabled() bool

func (*StandardOptions) IsDebugEnabled

func (o *StandardOptions) IsDebugEnabled() bool

func (*StandardOptions) IsFormattedCsvEnabled

func (o *StandardOptions) IsFormattedCsvEnabled() bool

func (*StandardOptions) IsFullOutputEnabled

func (o *StandardOptions) IsFullOutputEnabled() bool

func (*StandardOptions) IsHeaderDisabled

func (o *StandardOptions) IsHeaderDisabled() bool

func (*StandardOptions) IsHelpEnabled

func (o *StandardOptions) IsHelpEnabled() bool

func (*StandardOptions) IsLocalCertsEnabled

func (o *StandardOptions) IsLocalCertsEnabled() bool

func (*StandardOptions) IsNetDebugEnabled

func (o *StandardOptions) IsNetDebugEnabled() bool

func (*StandardOptions) IsNoAuthEnabled

func (o *StandardOptions) IsNoAuthEnabled() bool

func (*StandardOptions) IsNoRedirectEnabled

func (o *StandardOptions) IsNoRedirectEnabled() bool

func (*StandardOptions) IsOutputBodyEnabled

func (o *StandardOptions) IsOutputBodyEnabled() bool

func (*StandardOptions) IsOutputCookieEnabled

func (o *StandardOptions) IsOutputCookieEnabled() bool

func (*StandardOptions) IsOutputHeaderEnabled

func (o *StandardOptions) IsOutputHeaderEnabled() bool

func (*StandardOptions) IsOutputRequestEnabled added in v1.3.0

func (o *StandardOptions) IsOutputRequestEnabled() bool

func (*StandardOptions) IsOutputShortEnabled

func (o *StandardOptions) IsOutputShortEnabled() bool

func (*StandardOptions) IsPrettyPrintEnabled

func (o *StandardOptions) IsPrettyPrintEnabled() bool

func (*StandardOptions) IsQueryParamAuthEnabled

func (o *StandardOptions) IsQueryParamAuthEnabled() bool

func (*StandardOptions) IsReconnectEnabled

func (o *StandardOptions) IsReconnectEnabled() bool

func (*StandardOptions) IsSilentEnabled

func (o *StandardOptions) IsSilentEnabled() bool

func (*StandardOptions) IsSkipCertValidationEnabled

func (o *StandardOptions) IsSkipCertValidationEnabled() bool

func (*StandardOptions) IsVerboseEnabled

func (o *StandardOptions) IsVerboseEnabled() bool

func (*StandardOptions) IsWarmingEnabled

func (o *StandardOptions) IsWarmingEnabled() bool

func (StandardOptions) Set

func (o StandardOptions) Set(options ...int) StandardOptions

Set -- Return a copy of the standard options with the specified boolean options set to true

type StartupOptions

type StartupOptions struct {
	DebugInit         bool
	InitFileName      string
	InitFileExt       string
	ScriptFileExt     string
	AbortOnExceptions bool
}

StartupOptions -- configuration available to the shell

func GetDefaultStartupOptions

func GetDefaultStartupOptions() StartupOptions

GetDefaultStartupOptions return an interface to the options for the shell startup

type StringList

type StringList struct {
	Values []string
}

func (*StringList) Count

func (sl *StringList) Count() int

func (*StringList) GetValues

func (sl *StringList) GetValues() []string

func (*StringList) Set

func (sl *StringList) Set(value string, opt getopt.Option) error

func (*StringList) String

func (sl *StringList) String() string

type SubTopicInterface added in v1.4.2

type SubTopicInterface interface {
	WriteSubTopic(io.Writer, string) error
}

SubTopicInterface -- Some about topics may have sub topics

type SubstitutionFunction

type SubstitutionFunction struct {
	Name              string
	Group             string
	FunctionHelp      string
	FormatDescription string
	Formats           []SubstitutionItemHelp
	OptionDescription string
	Options           []SubstitutionItemHelp
	Function          SubstitutionHandler
	Example           string
}

SubstitutionFunction -- a registration function for a handler and its help

func GetSubstitutionFunction added in v1.4.0

func GetSubstitutionFunction(name string) (fn SubstitutionFunction, ok bool)

func SortedGroupSubstitutionFunctionList added in v1.4.0

func SortedGroupSubstitutionFunctionList(group string) []SubstitutionFunction

func SortedSubstitutionFunctionList added in v1.4.0

func SortedSubstitutionFunctionList(sortByGroup bool) []SubstitutionFunction

SortedSubstitutionFunctionList -- return the substitution functions in sorted order

type SubstitutionHandler

type SubstitutionHandler func(cache interface{}, funcName string, fmt string, option string) (value string, data interface{})

SubstitutionHandler -- A handler returns a value for substitution given a function name. The handler may be given a fmt string and option string to guide the appropriate formating of data. The raw data is returned enabling re-use of the same data when the same key is used with a function in the same function group).

type SubstitutionItemHelp

type SubstitutionItemHelp struct {
	Item        string
	Description string
}

SubstitutionItemHelp -- Help strucsture for a format

type TopicInterface added in v1.4.2

type TopicInterface interface {
	GetKey() string             // Key for lookup and sub-command
	GetTitle() string           // Title for help display
	GetDescription() string     // Decription of key in lists
	WriteAbout(io.Writer) error // The text to display about the topic
}

TopicInterface -- THe minumum supported interface for about topics

func GetTopics added in v1.4.2

func GetTopics() []TopicInterface

type Trackable

type Trackable interface {
	// DoNotCount - prevents the executed command to be counted as a command executed
	DoNotCount() bool
	// DoNotClearError - prevents the command from affecting the LastError state of a previous command
	DoNotClearError() bool
	// CommandCount - returns the number of commands this command may have executed
	CommandCount() int
}

Trackable - interface that overrides tracking mechanisms

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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