utils

package module
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2020 License: Apache-2.0 Imports: 18 Imported by: 0

README

Golang Utils

Go Build godoc Go Report Card codecov Quality Gate Status

Documentation

Index

Examples

Constants

View Source
const (
	UsernameKey = "username"
	PasswordKey = "password"
)
View Source
const (
	ConfigLoadedSuccessMsg    = "Configuration was loaded successfully from %s"
	ConfigChangeDetectedMsg   = "A configuration change was detected in the config file '%s'"
	ConfigUpdateSuccessMsg    = "Configuration was updated"
	ConfigUpdateFailedMsg     = "Configuration was not updated because of a validation failure"
	ConfigValidationFailedMsg = "Config validation failed"
)
View Source
const (
	PathNotFoundMsg      = "404 Path Not Found"
	MethodNotAllowedMsg  = "405 Method Not Allowed"
	InternalServerErrMsg = "500 Internal Server Error : Please contact your system administrator"
	StartingServerMsg    = "Starting the API server..."
	StartedServerMsg     = "The API server has started and is listening on %s"
)

Variables

View Source
var (
	// Skip TLS
	SkipTLS = false
	// ProxyEnabled enable proxy settings
	ProxyEnabled = false
	// ProxyProtocol protocol of the proxy server, http or https
	ProxyProtocol string
	// ProxyHost hostname of the proxy server
	ProxyHost string
	// ProxyPort port of the proxy server
	ProxyPort string
)
View Source
var LogLevel = infoLogLevel

LogLevel is the global variable to set the log level. Default value is INFO log level

Functions

func BasicAuthRequired

func BasicAuthRequired() gin.HandlerFunc

BasicAuthRequired is a gin middleware for checking if basic authentication is provided in the request The method writes the basic auth to the gin context The method returns an error if basic authentication is not set

func CountDuplicateEntries

func CountDuplicateEntries(list []string) map[string]int

CountDuplicateEntries counts the number of times a entry repeats in a slice of strings The function returns a map with the unique entries in the slice as keys and the duplicate frequencies of the unique entries of the slice

Example
slice := []string{"one", "two", "two", "three", "three", "three"}
fmt.Println(CountDuplicateEntries(slice))
Output:

map[one:1 three:3 two:2]

func CreateFile

func CreateFile(file string) (*os.File, error)

CreateFile creates a new file The method returns an error if there was an issue with creating an new file

func DuplicateEntryExists

func DuplicateEntryExists(stringSlice []string) bool

DuplicateEntryExists checks if a slice has duplicate entries or not The function returns a boolean response

true : the slice contains duplicate entries
func : the slice does not contain duplicate entries
Example
slice := []string{"one", "two", "two"}
fmt.Println(DuplicateEntryExists(slice))
Output:

true

func EntryExists

func EntryExists(slice []string, entry string) bool

EntryExists checks if an entry exists in a slice of strings The function returns a boolean value:

true if the entry exists or
false if the entry does not exist
Example
slice := []string{"one", "two", "three"}
fmt.Println(EntryExists(slice, "two"))
Output:

true

func FileExists

func FileExists(filePath string) bool

FileExists checks if a file exists and returns an error if the file was not found

func GetRandomPassword

func GetRandomPassword() string

GetRandomPassword generates a random string of upper + lower case alphabets and digits which is 23 bits long and returns the string

Example
password := GetRandomPassword()
fmt.Println(password)
Output:

func GetRequesterIP

func GetRequesterIP(r *http.Request) string

GetRequesterIP gets the requester IP from the request headers and returns the IP

func GetSliceEntryIndex

func GetSliceEntryIndex(slice []string, entry string) int

GetSliceEntryIndex returns the index of an entry in a slice of strings The function returns an integer value of the index of the first occurrence of the slice entry

Example
slice := []string{"one", "two", "three"}
fmt.Println(GetSliceEntryIndex(slice, "one"))
Output:

0

func OpenFile

func OpenFile(file string) (*os.File, error)

OpenFile opens a file The method returns an error if there is an issue with opening the file

func PromptConfirm

func PromptConfirm(name string) (string, error)

PromptConfirm prompts a confirmation menu on the console

func PromptMultiSelect

func PromptMultiSelect(name string, items []string) ([]string, error)

PromptMultiSelect prompts a multi-select menu on the console This is a combination of the PromptSelect and PromptConfirm modules

func PromptSelect

func PromptSelect(name string, items []string) (int, string, error)

PromptSelect prompts a select menu on the console

func PromptString

func PromptString(name string, validateFunc func(input string) error) (string, error)

PromptString prompts a input menu on the console

func ReadFile

func ReadFile(file string) ([]byte, error)

ReadFile checks if a file exists and if it does tries to reads the contents of the file and returns the data back The method returns an error the file does not exist or if there was an error in reading the contents of the file

func ReadJsonFile

func ReadJsonFile(filePath string, out interface{}) error

ReadJsonFile reads a yaml file and puts the contents into the out variables out variable should be a pointer to a valid struct The method returns and error if reading a file or the unmarshal process fails

func ReadYamlFile

func ReadYamlFile(filePath string, out interface{}) error

ReadYamlFile reads a yaml file and puts the contents into the out variables out variable should be a pointer to a valid struct The method returns and error if reading a file or the unmarshal process fails

func RemoveDuplicateEntries

func RemoveDuplicateEntries(stringSlice []string) []string

RemoveDuplicateEntries removes duplicate entries in a slice of strings The function returns back a slice with unique string entries

Example
slice := []string{"one", "two", "two", "three", "three", "three", "four", "four", "four", "four"}
fmt.Println(RemoveDuplicateEntries(slice))
Output:

[one two three four]

func RemoveEntryFromSlice

func RemoveEntryFromSlice(slice []string, entry string) []string

RemoveEntryFromSlice removes a entry from a slice of strings The function removed the first occurrence of the entry and then returns the updated slice back If the Entry does not exist then the function returns the same slice back

Example
slice := []string{"one", "two", "three"}
fmt.Println(RemoveEntryFromSlice(slice, "two"))
Output:

[one three]

func StatusString

func StatusString(code int) string

StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.

func WriteFile

func WriteFile(file string, data []byte) error

WriteFile creates a new file if the file does not exists and writes data into the file The method returns an error if there was an issue creating a new file or while writing data into the file

func WriteJSONFile

func WriteJSONFile(filePath string, in interface{}) error

WriteJSONFile encodes the data from a input interface into json format and writes the data into a file The in interface should be an address to a valid struct The method returns an error if there is an error with the json encode or with writing to the file

func WriteYamlFile

func WriteYamlFile(filePath string, in interface{}) error

WriteYamlFile encodes the data from a input interface into yaml format and writes the data into a file The in interface should be an address to a valid struct The method returns an error if there is an error with the yaml encode or with writing to the file

Types

type Auth

type Auth struct {
	Username string
	Password string
}

Auth represents authentication information

type CreateRequestError

type CreateRequestError struct {
	Err error
}

CreateRequestError represents an error when creating a http request fails

func (CreateRequestError) Error

func (cr CreateRequestError) Error() string

Error returns teh formatted CreateRequestError

type ErrResponse

type ErrResponse struct {
	Error string `json:"error"`
}

ErrResponse represents a generic http error response message

type FileCreateError

type FileCreateError struct {
	File string
	Err  error
}

FileCreateError represents an error when the code is not able to create a file

func (FileCreateError) Error

func (fc FileCreateError) Error() string

Error returns the formatted FileCreateError

type FileNotFoundError

type FileNotFoundError string

FileNotFoundError represents an error when the file is not found

func (FileNotFoundError) Error

func (fnf FileNotFoundError) Error() string

Error returns the formatted FileNotFoundError

type FileOpenError

type FileOpenError struct {
	File string
	Err  error
}

FileOpenError represents an error when the code is not able to open the file

func (FileOpenError) Error

func (fo FileOpenError) Error() string

Error returns the formatted FileOpenError

type FileReadError

type FileReadError struct {
	File string
	Err  error
}

FileReadError represents an error when the code is not able to read the file

func (FileReadError) Error

func (fr FileReadError) Error() string

Error returns the formatted FileReadError

type FileWriteError

type FileWriteError struct {
	File string
	Err  error
}

FileWriteError represents an error when the code is not able to write to the file

func (FileWriteError) Error

func (fw FileWriteError) Error() string

Error returns the formatted FileWriteError

type HTTPCnf

type HTTPCnf struct {
	SkipTLS       bool   `yaml:"skip_tls" mapstructure:"skip_tls"`
	ProxyEnable   bool   `yaml:"proxy_enable" mapstructure:"proxy_enable"`
	ProxyProtocol string `yaml:"proxy_protocol" mapstructure:"proxy_protocol"`
	ProxyHost     string `yaml:"proxy_host" mapstructure:"proxy_host"`
	ProxyPort     string `yaml:"proxy_port" mapstructure:"proxy_port"`
}

HTTPCnf represents the servers http configuration

func (*HTTPCnf) GetProxyUrl

func (hc *HTTPCnf) GetProxyUrl() string

GetProxyUrl returns the formatted proxy URL

func (*HTTPCnf) Set

func (hc *HTTPCnf) Set()

Set sets the http config

func (*HTTPCnf) Validate

func (hc *HTTPCnf) Validate() error

Validate checks if the values in the HTTPCnf are valid

type InvalidLogLevelError

type InvalidLogLevelError string

InvalidLogLevelError represents an error when the log level is not valid

func (InvalidLogLevelError) Error

func (ill InvalidLogLevelError) Error() string

Error returns the formatted InvalidLogLevelError

type InvalidProxyProtocolError

type InvalidProxyProtocolError string

InvalidProxyProtocolError represents an error when the proxy protocol is not valid

func (InvalidProxyProtocolError) Error

func (ipp InvalidProxyProtocolError) Error() string

Error returns the formatted InvalidProxyProtocolError

type JSONMarshalError

type JSONMarshalError struct {
	Err error
}

JSONMarshalError represents an error when json marshal fails

func (JSONMarshalError) Error

func (jm JSONMarshalError) Error() string

Error returns the formatted JSONMarshalError

type JSONUnMarshalError

type JSONUnMarshalError struct {
	Err error
}

JSONUnMarshalError represents an error when json unmarshal fails

func (JSONUnMarshalError) Error

func (jum JSONUnMarshalError) Error() string

Error returns the formatted JSONUnMarshalError

type LogFormatter

type LogFormatter struct {
	Request    *http.Request
	StatusCode int
	Msg        string
	ErrMsg     error
	Out        string
}

LogFormatter represents log message details

func (*LogFormatter) Debug

func (l *LogFormatter) Debug() *log.Logger

Debug generates the output log message and returns a new Debug logger

func (*LogFormatter) Error

func (l *LogFormatter) Error() *log.Logger

Error generates the output log message and returns a new Error logger

func (*LogFormatter) GetErrMsg

func (l *LogFormatter) GetErrMsg() string

GetErrMsg returns a formatted log message

func (*LogFormatter) GetLogMsg

func (l *LogFormatter) GetLogMsg() string

GetLogMsg formats a message based on the values set for Request and Message set for the Logger receiver If Request variable is nil only the message will be returned else a formatted string will the request details along with the message will be returned

func (*LogFormatter) GetMsg

func (l *LogFormatter) GetMsg() string

GetMsg returns a formatted log message

func (*LogFormatter) Info

func (l *LogFormatter) Info() *log.Logger

Info generates the output log message and returns a new Info logger

func (*LogFormatter) MethodColor

func (l *LogFormatter) MethodColor() string

MethodColor is the ANSI color for appropriately logging http method to a terminal.

func (*LogFormatter) ResetColor

func (l *LogFormatter) ResetColor() string

ResetColor resets all escape attributes.

func (*LogFormatter) StatusCodeColor

func (l *LogFormatter) StatusCodeColor() string

StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal.

func (*LogFormatter) Warn

func (l *LogFormatter) Warn() *log.Logger

Warn generates the output log message and returns a new Warn logger

type LoggerCnf

type LoggerCnf struct {
	Level string `json:"level" yaml:"level" mapstructure:"level"`
}

LoggerCnf represents the Logger settings

func (*LoggerCnf) Set

func (l *LoggerCnf) Set()

Set sets the log level

func (*LoggerCnf) Validate

func (l *LoggerCnf) Validate() error

Validate checks if the values in the LoggerCnf struct are valid The method returns an error if the configuration is not valid

type Logging

type Logging struct {
	Level string `json:"level" yaml:"level"`
}

Logging represents the logging configuration details

type MakeRequestError

type MakeRequestError struct {
	Err error
}

MakeRequestError represents an error when

func (MakeRequestError) Error

func (mr MakeRequestError) Error() string

Error returns teh formatted MakeRequestError

type MissingMandatoryParamError

type MissingMandatoryParamError []string

MissingMandatoryParamError represents an error when a mandatory parameter is missing

func (MissingMandatoryParamError) Error

func (mpe MissingMandatoryParamError) Error() string

Error returns the formatted MissingMandatoryParamError

type ProxyUrlParseError

type ProxyUrlParseError struct {
	Err error
}

ProxyUrlParseError represents an error when proxy url cannot be parsed

func (ProxyUrlParseError) Error

func (pup ProxyUrlParseError) Error() string

Error returns the formatted ProxyUrlParseError

type ReadConfigFileError

type ReadConfigFileError struct {
	File string
	Err  error
}

ReadConfigFileError represents an error when the config file cannot be read

func (ReadConfigFileError) Error

func (rcf ReadConfigFileError) Error() string

Error returns the formatted ReadConfigFileError

type ReadResponseError

type ReadResponseError struct {
	Err error
}

ReadResponseError represents an error when the response cannot be read

func (ReadResponseError) Error

func (rr ReadResponseError) Error() string

Error returns teh formatted ReadResponseError

type RegexCompileError

type RegexCompileError struct {
	Err error
}

RegexCompileError represents an error when a regex compilation fails

func (RegexCompileError) Error

func (rc RegexCompileError) Error() string

Error returns the formatted RegexCompileError

type Request

type Request struct {
	Url     string
	Method  string
	Auth    Auth
	Body    RequestBody
	Cnf     HTTPCnf
	Request *http.Request
	Result  Result
}

Request represents an HTTP request

func (*Request) HttpRequest

func (r *Request) HttpRequest() error

HttpRequest makes an http request to a remote server The response body and the status of the http response is registered into the request struct The method returns an error if there is a problem with making the request or while reading the response from the remote server

func (*Request) NewRequest

func (r *Request) NewRequest() error

NewRequest creates a base http request based on the URL method and credentials provided in the Request struct The method write the created request back into the Request struct The method returns an error if the request creation fails

type RequestBody

type RequestBody struct {
	Json []byte
	Text string
}

RequestBody body represents the format of a request body

type Response

type Response struct {
	Message string `json:"message"`
}

Response represents a generic http response message

type Result

type Result struct {
	Body   []byte
	Status string
}

Result represents the result of a http request

type ServerCnf

type ServerCnf struct {
	Host      string `yaml:"host" mapstructure:"host"`
	Port      string `yaml:"port" mapstructure:"port"`
	LoggerCnf `yaml:"logging" mapstructure:"logging"`
	HTTPCnf   `yaml:"http" mapstructure:"http"`
}

ServerCnf represents the server configuration It includes the basic host + port config along with the Logger and HTTP configurations

func (*ServerCnf) Validate

func (sc *ServerCnf) Validate() error

Validate validates if the sonar configuration provided in the configuration file is valid The method returns an error if any configuration defined in the receiver is not valid

type ValidationResult

type ValidationResult struct {
	Valid    bool     `json:"valid"`
	Messages []string `json:"messages"`
}

ValidationResult represents the result of validation method

type YAMLMarshalError

type YAMLMarshalError struct {
	Err error
}

YAMLMarshalError represents an error when yaml marshal fails

func (YAMLMarshalError) Error

func (ym YAMLMarshalError) Error() string

Error returns the formatted YAMLMarshalError

type YAMLUnMarshalError

type YAMLUnMarshalError struct {
	Err error
}

YAMLUnMarshalError represents an error when yaml unmarshal fails

func (YAMLUnMarshalError) Error

func (yum YAMLUnMarshalError) Error() string

Error returns the formatted YAMLUnMarshalError

Jump to

Keyboard shortcuts

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