goat

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2019 License: MIT Imports: 37 Imported by: 0

README

goat

Goat is a collection of helper structs and functions for Go web apps

demo

A basic demo app can be found in the demo directory. To run it, change into the directory and run:

dep ensure
./run.sh

Running the demo app will print some information on how to use Goat.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AssertValidID

func AssertValidID(t *testing.T, id ID)

func AssertValidInitialCreatedAt

func AssertValidInitialCreatedAt(t *testing.T, d time.Time)

func AssertValidInitialDeletedAt

func AssertValidInitialDeletedAt(t *testing.T, d *time.Time)

func AssertValidInitialUpdatedAt

func AssertValidInitialUpdatedAt(t *testing.T, d *time.Time)

func AssertValidModifiedUpdatedAt

func AssertValidModifiedUpdatedAt(t *testing.T, d *time.Time)

func BindRequestMiddleware

func BindRequestMiddleware(req interface{}) gin.HandlerFunc

Validates an incoming request and binds the request body to the provided struct if the validation passes.

Returns a 400 error with validation errors if binding fails.

Sets the bound request as an interface{} in the Gin registry if binding succeeds. You can retrieve in your handlers it like this:

r, ok := goat.GetRequest(c).(*yourRequestStruct)

This middleware allows you to annotate your request struct fields with `binding:"required"` to make required fields.

@TODO it seems that if a request struct has a field that is named the same as one of it's child struct's fields that the validation messages don't prefix the field name with child struct's name

func CWD

func CWD() string

func ConfigFileName

func ConfigFileName() string

func ConfigFilePath

func ConfigFilePath() string

func EnvBool

func EnvBool(s string, defaultValue bool) bool

func EnvString

func EnvString(s string, defaultValue string) string

func ErrorsBesidesRecordNotFound

func ErrorsBesidesRecordNotFound(errs []error) bool

Returns true if there are any errors in the provided array that are NOT a 'record not found' error

func ErrorsToError

func ErrorsToError(errs []error) error

func ErrorsToString

func ErrorsToString(errs []error) string

func ErrorsToStrings

func ErrorsToStrings(errs []error) []string

func ExeDir

func ExeDir() string

func ExePath

func ExePath() string

func ExitIfProduction

func ExitIfProduction()

func ExitSuccess

func ExitSuccess()

func ExitWithError

func ExitWithError(err error)

func ExitWithErrors

func ExitWithErrors(errs []error)

func GenerateToken

func GenerateToken() string

Returns a random string that can be used as a token.

func GetCountArg

func GetCountArg(countArg string) (int, error)

func GetErrors

func GetErrors() []error

func GetRequest

func GetRequest(c *gin.Context) interface{}

Returns true and a request object from the Gin context created by the bindRequestMiddleware. If the request is not set, false is returned and 500 response headers are set.

func GetStructFieldValidationMeta

func GetStructFieldValidationMeta(strct reflect.Type, e *validator.FieldError) (string, string, error)

func HandleCSVRows

func HandleCSVRows(path string, skipHeaderRow bool, breakOnEOF bool, callback func(line []string, eof bool) error) error

func HasErrors

func HasErrors() bool

func Init

func Init() []error

func MustEnvInt

func MustEnvInt(s string, defaultValue int) int

func NewCustomDB

func NewCustomDB(c DBConfig) (*gorm.DB, error)

Returns a new database connection using the provided connection info. Will panic if goat has not been initialized and add an error to the error stack if the connection fails.

func NewCustomLogger

func NewCustomLogger(l string) *logrus.Logger

Returns an arbitrarily named logger instance. If not configured directly in the app config under "logs.<name>", goes to <binary path>/logs/<name>.log. Will panic if goat.Init() has not been called, since the app root path is needed to create the log file.

func NewDB

func NewDB() (*gorm.DB, error)

Database connection constructor. Will attempt to connect to a database using connection info from the app config. Will panic if goat has not been initialized and add an error to the error stack if the connection fails.

func NewLogger

func NewLogger() *logrus.Logger

System Logger constructor. Returns a new logger instance writing to <binary path>/logs/sys.log, unless configured otherwise in the app config file under "logs.sys". Will panic if goat.Init() has not been called, since the app root path is needed to create the log file.

func NewSTDOutLogger

func NewSTDOutLogger() *logrus.Logger

Return a new std out logger.

func OpenCSV

func OpenCSV(path string) (reader *csv.Reader, err error)

func PrependErrors

func PrependErrors(errs []error, err error) []error

func PrintFail

func PrintFail(s string)

func PrintHeading

func PrintHeading(s string)

func PrintIndent

func PrintIndent(s string)

func PrintInfo

func PrintInfo(s string)

func PrintSuccess

func PrintSuccess(s string)

func PrintWarning

func PrintWarning(s string)

func RandomBool

func RandomBool() bool

func RandomDecimal

func RandomDecimal(min, max int64) decimal.Decimal

func RandomDecimalExp

func RandomDecimalExp(min, max int64, exp int32) decimal.Decimal

func RandomIndex

func RandomIndex(length int) int

func RandomInt

func RandomInt(min, max int) int

func RandomInt32

func RandomInt32(min, max int32) int32

func RandomInt64

func RandomInt64(min, max int64) int64

func ReadConfig

func ReadConfig(b bool)

func RecordNotFound

func RecordNotFound(errs []error) bool

func RequireDecimalEqual

func RequireDecimalEqual(t *testing.T, exp, act interface{}, msgAndArgs ...interface{})

func RespondAuthenticationError

func RespondAuthenticationError(c *gin.Context)

func RespondBadRequest

func RespondBadRequest(c *gin.Context, data interface{})

func RespondBadRequestError

func RespondBadRequestError(c *gin.Context, err error)

func RespondBadRequestErrors

func RespondBadRequestErrors(c *gin.Context, errs []error)

func RespondCreated

func RespondCreated(c *gin.Context, data interface{})

func RespondData

func RespondData(c *gin.Context, data interface{})

func RespondInvalid

func RespondInvalid(c *gin.Context)

func RespondMessage

func RespondMessage(c *gin.Context, m string)

func RespondNotFoundError

func RespondNotFoundError(c *gin.Context, err error)

func RespondNotFoundErrors

func RespondNotFoundErrors(c *gin.Context, errs []error)

func RespondRequestValidationError

func RespondRequestValidationError(c *gin.Context, err error, t reflect.Type)

func RespondServerError

func RespondServerError(c *gin.Context, err error)

func RespondServerErrors

func RespondServerErrors(c *gin.Context, errs []error)

func RespondUnauthorizedError

func RespondUnauthorizedError(c *gin.Context)

func RespondValid

func RespondValid(c *gin.Context)

func RespondValidationError

func RespondValidationError(c *gin.Context, errs map[string]error)

func Root

func Root() string

func RootPath

func RootPath(path string) string

func SetConfigFile

func SetConfigFile(filename string) error

func SetConfigFilePath

func SetConfigFilePath(path string) error

func SetDBPanicMode

func SetDBPanicMode(b bool)

Set whether or not to panic if a database connection fails. Default is true. Will panic if goat has not been initialized.

func SetJSONTagExcludedStructs

func SetJSONTagExcludedStructs(s []string)

Set structs that will be skipped while traversing structs to find field json names. Do this to avoid needlessly traversing struct fields.

func SetRoot

func SetRoot(p string)

Set the project root path manually, overriding the default, which is the path to the running executable.

func TimeToPrettyString

func TimeToPrettyString(t time.Time) string

func TimeToYMDHISString

func TimeToYMDHISString(t time.Time) string

func TimeToYMDString

func TimeToYMDString(t time.Time) string

func ValidPort

func ValidPort(port string) (valid bool, message string)

Determines whether the provided value is a valid port that can be listened on.

func YMDHISStringToTime

func YMDHISStringToTime(str string) (time.Time, error)

func YMDStringToTime

func YMDStringToTime(str string) (time.Time, error)

Types

type BoolResponse

type BoolResponse struct {
	Valid bool `json:"valid"`
}

A boolean response. swagger:response BoolResponse

type Container

type Container struct {
	Utils  utilsInterface
	Config configInterface
	Path   pathInterface
}

type ContextResponder

type ContextResponder func(c *gin.Context)

type DBConfig

type DBConfig struct {
	Host            string
	Port            int
	Database        string
	Username        string
	Password        string
	Debug           bool
	MultiStatements bool
}

func GetDefaultDBConfig

func GetDefaultDBConfig() DBConfig

func (*DBConfig) String

func (d *DBConfig) String() string

type ErrorHandler

type ErrorHandler interface {
	HandleContext(c *gin.Context, m string, responder ContextResponder)
	HandleMessage(c *gin.Context, m string, responder ErrorResponder)
	HandleError(c *gin.Context, err error, responder ErrorResponder)
	HandleErrorM(c *gin.Context, err error, m string, responder ErrorResponder)
	HandleErrors(c *gin.Context, errs []error, responder ErrorResponder)
	HandleErrorsM(c *gin.Context, errs []error, m string, responder ErrorResponder)
}

func NewErrorHandler

func NewErrorHandler(l *logrus.Logger) ErrorHandler

type ErrorHandlerGin

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

func (ErrorHandlerGin) HandleContext

func (h ErrorHandlerGin) HandleContext(c *gin.Context, m string, responder ContextResponder)

func (ErrorHandlerGin) HandleError

func (h ErrorHandlerGin) HandleError(c *gin.Context, err error, responder ErrorResponder)

func (ErrorHandlerGin) HandleErrorM

func (h ErrorHandlerGin) HandleErrorM(c *gin.Context, err error, m string, responder ErrorResponder)

func (ErrorHandlerGin) HandleErrors

func (h ErrorHandlerGin) HandleErrors(c *gin.Context, errs []error, responder ErrorResponder)

func (ErrorHandlerGin) HandleErrorsM

func (h ErrorHandlerGin) HandleErrorsM(c *gin.Context, errs []error, m string, responder ErrorResponder)

func (ErrorHandlerGin) HandleMessage

func (h ErrorHandlerGin) HandleMessage(c *gin.Context, m string, responder ErrorResponder)

type ErrorResponder

type ErrorResponder func(c *gin.Context, e error)

type HandlerTest

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

func NewHandlerTest

func NewHandlerTest(r *Router) *HandlerTest

func (*HandlerTest) Body

func (h *HandlerTest) Body(data *map[string]interface{}) *HandlerTest

Set the body for the current request.

func (*HandlerTest) Delete

func (h *HandlerTest) Delete(url string) *HandlerTest

func (*HandlerTest) DeleteF

func (h *HandlerTest) DeleteF(urlf string, a ...interface{}) *HandlerTest

func (*HandlerTest) Get

func (h *HandlerTest) Get(url string) *HandlerTest

func (*HandlerTest) GetF

func (h *HandlerTest) GetF(urlf string, a ...interface{}) *HandlerTest

func (*HandlerTest) Headers

func (h *HandlerTest) Headers(headers map[string]string) *HandlerTest

Set the headers for the current request.

func (*HandlerTest) Post

func (h *HandlerTest) Post(url string) *HandlerTest

func (*HandlerTest) PostF

func (h *HandlerTest) PostF(urlf string, a ...interface{}) *HandlerTest

func (*HandlerTest) Put

func (h *HandlerTest) Put(url string) *HandlerTest

func (*HandlerTest) PutF

func (h *HandlerTest) PutF(urlf string, a ...interface{}) *HandlerTest

func (*HandlerTest) Request

func (h *HandlerTest) Request(method, url string) *HandlerTest

func (*HandlerTest) RequestF

func (h *HandlerTest) RequestF(method, urlf string, a ...interface{}) *HandlerTest

func (*HandlerTest) Send

func (h *HandlerTest) Send() *HandlerTestResponse

Returns the result of sending the current request. Panics if the request creation fails.

func (*HandlerTest) SetRemoteAddr

func (h *HandlerTest) SetRemoteAddr(ip string)

Overwrite the default remote address to use when sending requests.

type HandlerTestResponse

type HandlerTestResponse struct {
	*httptest.ResponseRecorder
	BodyString string
}

func (*HandlerTestResponse) Map

func (r *HandlerTestResponse) Map(m interface{}) error

Map a handler test response to the provided struct.

type ID

type ID uuid.UUID

A UUID type that implements a custom Value function for storing UUIDs as binary(16) columns in the database.

func NewID

func NewID() ID

func NilID

func NilID() ID

func ParseAllIDs

func ParseAllIDs(s []string) ([]ID, error)

func ParseID

func ParseID(s string) (ID, error)

func (ID) MarshalBinary

func (id ID) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler.

func (ID) MarshalText

func (id ID) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*ID) Scan

func (id *ID) Scan(src interface{}) error

func (ID) String

func (id ID) String() string

func (*ID) UnmarshalBinary

func (id *ID) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler.

func (*ID) UnmarshalText

func (id *ID) UnmarshalText(data []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

func (ID) Valid

func (id ID) Valid() bool

func (ID) Value

func (id ID) Value() (driver.Value, error)

type Model

type Model struct {
	ID        ID         `json:"id" gorm:"primary_key"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt *time.Time `json:"updated_at"`
	DeletedAt *time.Time `json:"deleted_at"`
}

func (Model) BeforeCreate

func (m Model) BeforeCreate(scope *gorm.Scope) error

type RequestValidator

type RequestValidator struct {
	*validator.Validate
}

func (*RequestValidator) ValidateStruct

func (v *RequestValidator) ValidateStruct(i interface{}) error

type Response

type Response struct {
	Message string                 `json:"message"`
	Errors  []string               `json:"errors,omitempty"`
	Data    map[string]interface{} `json:"data,omitempty"`
}

A generic response. swagger:response Response

type Router

type Router struct {
	Mode       string
	Engine     *gin.Engine
	RoutesFunc func(*Router)
	DB         *gorm.DB
	// contains filtered or unexported fields
}

func NewRouter

func NewRouter(mode string, getRoutes func(*Router)) *Router

Router constructor. Will panic if goat has not been initialized.

func (*Router) Run

func (r *Router) Run(addr ...string) error

Run the Gin engine.

func (*Router) SetConfig

func (r *Router) SetConfig(d map[string]interface{})

Set a map of key-value pairs that will be added to the Gin registry when the router initializes.

type ValidationResponse

type ValidationResponse struct {
	Message string            `json:"message"`
	Errors  map[string]string `json:"errors,omitempty"`
}

A validation error response. swagger:response ValidationResponse

Directories

Path Synopsis
bar
foo
tests
cli_config command

Jump to

Keyboard shortcuts

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