goapp

package module
v1.0.7 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2025 License: MIT Imports: 25 Imported by: 6

README

goapp - MiTo Team's Golang projects application base

Reference GitHub code size Go Report Card GitHub

GitHub Version GitHub Release GitHub commit activity

Go projects application base

Add as git submodule

git submodule add -b main https://github.com/mitoteam/goapp.git internal/goapp

Disable commit hash tracking for submodule in .gitmodules :

[submodule "goapp"]
    ignore = all # ignore hash changes

Add use ./internal/goapp to main project go.work

Do go mod tidy

Useful commands

Pull main project with submodules:

git pull --recurse-submodules

Documentation

Index

Constants

View Source
const DEV_MODE_LABEL = "DEV"
View Source
const MOTTO = "Making world better since 2005"

Variables

View Source
var (
	BuildVersion = DEV_MODE_LABEL
	BuildCommit  = DEV_MODE_LABEL
	BuildTime    = DEV_MODE_LABEL
)

Variables to be set by compiler

View Source
var DbSchema *dbSchemaType

Functions

func CountOL

func CountOL[ModelT any]() (cnt int64)

Counts records for model (O)bjects using prepared gorm TX - PreQuery(). if gorm TX was not prepared, empty one is created (counting all model objects)

func CreateObject

func CreateObject(modelObject any) bool

Inserts new record for object. Used for objects without ID to force creation. Normal objects should use SaveObject() for both inserting and updating. Returns false if something goes wrong.

func DeleteObject

func DeleteObject(modelObject any) error

Deletes object. Returns false if something goes wrong.

func FirstO

func FirstO[ModelT any]() (r *ModelT)

Loads first available model object. Conditions can be set in PreQuery(). Returns nil if object was not loaded.

func LoadO

func LoadO[ModelT any](id any) (r *ModelT)

Loads model object by ID. Returns nil if object was not loaded.

func LoadOL

func LoadOL[ModelT any]() (list []*ModelT)

Loads model (O)bjects (L)ist using prepared gorm TX - PreQuery(). if gorm TX was not prepared, empty one is created (selecting all model objects)

func LoadOMust

func LoadOMust[ModelT any](id any) (r *ModelT)

Works like LoadO() but panics if object was not found.

func LoadOrCreateO

func LoadOrCreateO[ModelT any](id any) (r *ModelT)

If id == 0 creates new empty object. Loads model object by ID otherwise.

func PreQuery

func PreQuery[ModelT any]() (tx *gorm.DB)

Prepares gorm TX for loading model (O)bjects (L)ist. Returned TX can be used to apply conditions and other gorm query clauses.

func SaveObject

func SaveObject(modelObject any) bool

Saves object. Returns false and adds message to log if something goes wrong.

func SaveObjectE added in v1.0.2

func SaveObjectE(modelObject any) error

Saves object. Returns err if something goes wrong or nil on success.

func Transaction

func Transaction(trxF func() error)

Just a simple wrapper

Types

type ApiRequest

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

func (*ApiRequest) GetInData

func (r *ApiRequest) GetInData(name string) string

func (*ApiRequest) GetInDataInt

func (r *ApiRequest) GetInDataInt(name string, default_value int) int

func (*ApiRequest) GetOutData

func (r *ApiRequest) GetOutData(name string) string

func (*ApiRequest) Session

func (r *ApiRequest) Session() sessions.Session

func (*ApiRequest) SessionClear

func (r *ApiRequest) SessionClear()

func (*ApiRequest) SessionGet

func (r *ApiRequest) SessionGet(key string) any

func (*ApiRequest) SessionSet

func (r *ApiRequest) SessionSet(key string, value any)

func (*ApiRequest) SetErrorStatus

func (r *ApiRequest) SetErrorStatus(message string)

func (*ApiRequest) SetOkStatus

func (r *ApiRequest) SetOkStatus(message string)

func (*ApiRequest) SetOutData

func (r *ApiRequest) SetOutData(name string, value interface{})

type ApiRequestHandler

type ApiRequestHandler func(r *ApiRequest) error

type AppBase

type AppBase struct {
	ExecutableName  string //executable command name
	AppName         string //Long name
	LongDescription string //Long description

	Version         string    //Version (auto set by compiler)
	BuildCommitFull string    //Git full commit hash
	BuildCommit     string    //Git short commit hash
	BuildTime       string    //Build time
	BuildWith       string    //Build information
	StartTime       time.Time //Startup timestamp

	License string //License information to print with `license` command

	Global map[string]interface{} //some global application state values

	AppSettingsFilename string      // with .yml extension please
	AppSettings         interface{} //pointer to struct embedding AppSettingsBase

	//base app context to be used
	BaseContext context.Context

	//timeout for webserver shutdown
	ShutdownTimeout time.Duration

	WebRouterLogRequests bool                // true = extended web request logging (--log-request option of `run`)
	BuildWebRouterF      func(r *gin.Engine) // function to build web router for `run` command

	//web api
	WebApiPathPrefix string // usually "/api". Leave empty to disable web API at all.
	WebApiEnableGet  bool   // Serve both POST and GET methods. Default 'false' = POST-requests only.

	//callbacks (aka event handlers)
	PreCmdF  func(cmd *cobra.Command) error // called before any subcommand. Stops executions if error returned.
	PostCmdF func(cmd *cobra.Command) error // called after any subcommand. Stops executions if error returned.

	PreRunF    func() error // called before starting `run` command. Stops executions if error returned.
	PostRunF   func() error // called after finishing `run` command. Stops executions if error returned.
	InitF      func() error // Additional code for `init` subcommand. Stops executions if error returned.
	PrintInfoF func()       // Prints additional information when `info` subcommand called.

	BuildCustomCommandsF func(rootCmd *cobra.Command) // Set this to add any custom subcommands
	// contains filtered or unexported fields
}

func NewAppBase

func NewAppBase(defaultSettings interface{}) *AppBase

Initializes new application. settings - application settings default values. Pointer to struct that embeds AppSettingsBase.

func (*AppBase) ApiHandler

func (app *AppBase) ApiHandler(path string, handler ApiRequestHandler) *AppBase

func (*AppBase) Handler

func (app *AppBase) Handler() http.Handler

func (*AppBase) IsDevMode

func (app *AppBase) IsDevMode() bool

func (*AppBase) Run

func (app *AppBase) Run()

func (*AppBase) SetHandler

func (app *AppBase) SetHandler(h http.Handler)

func (*AppBase) Uptime added in v1.0.4

func (app *AppBase) Uptime() time.Duration

type AppSettingsBase

type AppSettingsBase struct {
	LoadedFromFile bool `yaml:"-"` //ignored in yaml

	Production bool `yaml:"production" yaml_comment:"Production mode"`

	BaseUrl string `yaml:"base_url" yaml_comment:"Base external site URL (with protocol and port, no trailing slash)"`

	WebserverHostname     string `yaml:"webserver_hostname" yaml_comment:"Webserver hostname"`
	WebserverPort         uint16 `yaml:"webserver_port" yaml_comment:"Webserver port number"`
	WebserverCookieSecret string `yaml:"webserver_cookie_secret" yaml_comment:"Secret string to encrypt cookies. Required in Production mode."`

	ServiceName  string `yaml:"service_name" yaml_comment:"Service name for 'install' command"`
	ServiceUser  string `yaml:"service_user" yaml_comment:"User for 'install' command"`
	ServiceGroup string `yaml:"service_group" yaml_comment:"Group for 'install' command"`

	InitialRootPassword string `` /* 157-byte string literal not displayed */

	LogSql bool `yaml:"log_sql" yaml_comment:"Log SQL queries."`
}

type BaseModel

type BaseModel struct {
	DbModel

	ID        int64 `gorm:"primaryKey;not null"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

gorm.Model alternative without DeletedAt column (to disable Soft Delete feature) see https://gorm.io/docs/delete.html#Soft-Delete

type DbModel

type DbModel struct {
}

base model type all model types should embed

type WorkerPool

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

func StartWorkerPool

func StartWorkerPool(ctx context.Context, workersCount int) *WorkerPool

func (*WorkerPool) DoJobList

func (wp *WorkerPool) DoJobList(jobList []WorkerPoolJob, wait bool)

func (*WorkerPool) DoSingleJob

func (wp *WorkerPool) DoSingleJob(job WorkerPoolJob, wait bool)

func (*WorkerPool) Stop

func (wp *WorkerPool) Stop()

type WorkerPoolJob

type WorkerPoolJob interface {
	Do()
}

Jump to

Keyboard shortcuts

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