Documentation
¶
Overview ¶
Package gomvc is a Golang package easy to use and build almost any MVC Web App connected to MySql database with just a few steps. `gomvc` package requires a MySql Server up and running and a database ready to drive your web application.
Build a standard MVC (Model, View, Controller) style web app with minimum Golang code, like you use a classic MVC Framework. Many features, many ready to use functions, highly customizable, embeded log and error handling
#### MVC
``` (databse CRUD) (http req/resp)
Model <--------> Controller
\ /
\ /
\ /
\ /
\ /
View
(text/template files)
```
#### Basic Steps * Edit the config file * Load config file `config.yaml` * Connect to MySql database * Write code to initialize your Models and Controllers * Write your standard text/Template files (Views) * Start your server and enjoy
#### More Examples Find mire examples in Readme.md file
Firewall detection and notification
Index ¶
- Constants
- Variables
- func BuildQuery(queryType QueryType, fields []SQLField, table SQLTable, joins []SQLJoin, ...) (string, []interface{})
- func BuildQueryExtended(queryType QueryType, fields []SQLField, table SQLTable, joins []SQLJoin, ...) (string, []interface{})
- func CenterText(text string, length int, deco rune) string
- func CenterTextSpaced(text string, length int, deco rune) string
- func CheckExist(data []interface{}, searchString, trueValue, falseValue string) string
- func CheckValue(data []interface{}, searchKey, expectedValue, trueValue, falseValue string) string
- func ConnectDatabase(cfg DatabaseConf) (*sql.DB, error)
- func ConnectDatabaseSQLite(dbname string) (*sql.DB, error)
- func CreateBanner(title, subtitle string, width int, deco rune) []string
- func CreateBox(text string, width int, deco rune) []string
- func DisplayFirewallHelp(port int)
- func ExtractBetween(str, start, end string) string
- func FindInSlice(slice []string, value string) int
- func FindValue(data []interface{}, searchKey string) string
- func GetPageNameFromRequest(r *http.Request) string
- func IncNumber(i int) int
- func InfoMessage(info string)
- func InitHelpers(appcfg *AppConfig)
- func ServerError(w http.ResponseWriter, err error)
- type Action
- type ActionRouting
- type AppConfig
- type AuthCondition
- type AuthObject
- func (a *AuthObject) CheckPasswordHash(password, hash string) bool
- func (a *AuthObject) GetExpirationFromNow() time.Time
- func (a *AuthObject) HashPassword(password string) (string, error)
- func (a *AuthObject) IsSessionExpired(r *http.Request) (bool, error)
- func (a *AuthObject) KillAuthSession(w http.ResponseWriter, r *http.Request) error
- func (a *AuthObject) TokenGenerator() string
- type Controller
- func (c *Controller) AddTemplateData(td TemplateData, r *http.Request) TemplateData
- func (c *Controller) CreateTemplateCache(homePageFileName string, layoutTemplateFileName string) error
- func (c *Controller) GetAuthObject() *AuthObject
- func (c *Controller) GetFunctions() template.FuncMap
- func (c *Controller) GetLinuxUsername(r *http.Request) string
- func (c *Controller) GetSession() *scs.SessionManager
- func (c *Controller) GetTemplate(page string) (*template.Template, error)
- func (c *Controller) GetUnderConstructionTemplate(page string) (*template.Template, error)
- func (c *Controller) Initialize(db *sql.DB, cfg *AppConfig)
- func (c *Controller) IsSessionLinuxAuth(r *http.Request) bool
- func (c *Controller) RegisterAction(route ActionRouting, action Action, model *Model)
- func (c *Controller) RegisterAuthAction(authURL string, nextURL string, model *Model, authObject AuthObject)
- func (c *Controller) RegisterAuthActionLinux(authURL string, nextURL string, authObject AuthObject)
- func (c *Controller) RegisterCustomAction(route ActionRouting, method int, model *Model, f http.HandlerFunc)
- func (c *Controller) View(t *template.Template, td *TemplateData, w http.ResponseWriter, r *http.Request)
- type DatabaseConf
- type Filter
- type FirewallInfo
- type JoinType
- type Model
- func (m *Model) AddRelation(db *sql.DB, tableName string, PKField string, keys SQLKeyPair, ...)
- func (m *Model) AssignLabels(labels map[string]string)
- func (m *Model) Delete(id string) (bool, error)
- func (m *Model) Execute(q string, values ...interface{}) ([]ResultRow, error)
- func (m *Model) GetLastId() (int64, error)
- func (m *Model) GetRecords(filters []Filter, limit int64) ([]ResultRow, error)
- func (m *Model) InitModel(db *sql.DB, tableName string, PKField string) error
- func (m *Model) Insert(fields []SQLField) (bool, error)
- func (m *Model) Instance() Model
- func (m *Model) Label(field string) string
- func (m *Model) NewQueryBuilder() *QueryBuilder
- func (m *Model) Save(fields []SQLField) (bool, error)deprecated
- func (m *Model) Update(fields []SQLField, id string) (bool, error)
- type QueryBuilder
- func (qb *QueryBuilder) Count() (int64, error)
- func (qb *QueryBuilder) Execute() ([]ResultRow, error)
- func (qb *QueryBuilder) First() (ResultRow, error)
- func (qb *QueryBuilder) GroupBy(columns ...string) *QueryBuilder
- func (qb *QueryBuilder) Join(foreignTable, foreignPK, localKey, foreignKey string) *QueryBuilder
- func (qb *QueryBuilder) LeftJoin(foreignTable, foreignPK, localKey, foreignKey string) *QueryBuilder
- func (qb *QueryBuilder) Limit(limit int64) *QueryBuilder
- func (qb *QueryBuilder) Offset(offset int64) *QueryBuilder
- func (qb *QueryBuilder) OrWhere(field, operator string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) OrderBy(column, direction string) *QueryBuilder
- func (qb *QueryBuilder) Select(columns ...string) *QueryBuilder
- func (qb *QueryBuilder) Where(field, operator string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) WhereIn(field string, values []interface{}) *QueryBuilder
- type QueryType
- type RateLimitConf
- type RateLimiter
- func (rl *RateLimiter) GetBlockedUntil(identifier string) time.Time
- func (rl *RateLimiter) GetRemainingAttempts(identifier string) int
- func (rl *RateLimiter) GetStats() map[string]interface{}
- func (rl *RateLimiter) IsBlocked(identifier string) bool
- func (rl *RateLimiter) RecordFailedAttempt(identifier string)
- func (rl *RateLimiter) ResetAttempts(identifier string)
- type Relation
- type RequestObject
- type ResultRow
- type ResultStyle
- type SQLField
- type SQLJoin
- type SQLKeyPair
- type SQLTable
- type ServerConf
- type TemplateData
- type TemplateObject
Constants ¶
const ( HttpGET int = 0 HttpPOST int = 1 )
HttpGET, HttpPOST constants are helping the use of the package when it comes to the type of request
Variables ¶
var Session *scs.SessionManager
Session is the SessionManager that will work as a middleware.
Functions ¶
func BuildQuery ¶
func BuildQuery(queryType QueryType, fields []SQLField, table SQLTable, joins []SQLJoin, wheres []Filter, group string, order string, limit int64) (string, []interface{})
Build query func
func BuildQueryExtended ¶ added in v1.2.5
func BuildQueryExtended(queryType QueryType, fields []SQLField, table SQLTable, joins []SQLJoin, wheres []Filter, group string, order string, limit int64, offset int64) (string, []interface{})
BuildQueryExtended - improved version with OFFSET and IN clause support
func CenterText ¶ added in v1.2.5
CenterText centers a string within a specified width and surrounds it with a decorator character Examples:
CenterText("Hello", 20, '=') → "====== Hello ======="
CenterText("GoMVC", 30, '-') → "------------ GoMVC ------------"
CenterText("Title", 15, '*') → "**** Title *****"
func CenterTextSpaced ¶ added in v1.2.5
CenterTextSpaced centers text with spaces and adds decorators at edges Examples:
CenterTextSpaced("Hello", 20, '|') → "| Hello |"
CenterTextSpaced("GoMVC", 30, '*') → "* GoMVC *"
func CheckExist ¶ added in v1.2.5
CheckExist checks if a search string exists anywhere in the data Returns trueValue if found, falseValue if not found Example: CheckExist(data, "installed", "Yes", "No") Example: CheckExist(data, "running", "Active", "Inactive")
func CheckValue ¶ added in v1.2.5
CheckValue searches for a key in section data and returns trueValue if found and matches expected, otherwise returns falseValue Example: CheckValue(data, "Status", "running", "Running", "Stopped")
func ConnectDatabaseSQLite ¶ added in v1.2.5
ConnectDatabase
func CreateBanner ¶ added in v1.2.5
CreateBanner creates a multi-line banner with title and subtitle Example:
banner := CreateBanner("GoMVC Server", "Port 8080", 40, '=')
for _, line := range banner {
fmt.Println(line)
}
func CreateBox ¶ added in v1.2.5
CreateBox creates a boxed text with decorators Example:
lines := CreateBox("Hello", 15, '=')
for _, line := range lines {
fmt.Println(line)
}
Output:
===============
=====Hello=====
===============
func DisplayFirewallHelp ¶ added in v1.2.5
func DisplayFirewallHelp(port int)
DisplayFirewallHelp displays helpful firewall information
func ExtractBetween ¶ added in v1.2.5
ExtractBetween extracts the text between two characters/strings Example: ExtractBetween("Used RAM: 3.2Gi (42.1%)", "(", ")") returns "42.1%"
func FindInSlice ¶
FindInSlice find a value in a slice and return the index
func FindValue ¶ added in v1.2.5
====================================================================== Template ready functions ====================================================================== FindValue searches for a key in the section data and returns its value
func GetPageNameFromRequest ¶ added in v1.2.5
GetPageNameFromRequest extracts the page name from the request URL in order to add it in every page
func InfoMessage ¶
func InfoMessage(info string)
InfoMessage print/log an INFO message -> send to info logger
func InitHelpers ¶
func InitHelpers(appcfg *AppConfig)
InitHelpers is the function to call in order to build the Helpers
func ServerError ¶
func ServerError(w http.ResponseWriter, err error)
ServerError print/log a Server error -> send to error logger
Types ¶
type Action ¶
type Action int
Action defines the type of action to execute from a handler. ActionVew = return data to http client ActionCreate, ActionUpdate, ActionDelete = create, update, delete records from database, this action are more likeky to accompaned with an ActionView action so they return a result to the http client after the action
type ActionRouting ¶
ActionRouting helps the router to have the routing information about the URL, the NextURL, if the route needs authentication or if it is a web hook (web hook can have POST data without midleware CSRF check)
type AppConfig ¶
type AppConfig struct {
UseCache bool
Server ServerConf
Database DatabaseConf
EnableInfoLog bool
ShowStackOnError bool
RateLimit RateLimitConf
}
AppConfig is the application config,
func ReadConfig ¶
ReadConfig this function is for reading the configuration file
type AuthCondition ¶
AuthCondition is the struct for the ExtraConditions field in the AuthObject struct.
type AuthObject ¶
type AuthObject struct {
Model Model
UsernameFieldName string
PasswordFieldName string
HashCodeFieldName string
ExpTimeFieldName string
SessionKey string
ExpireAfterIdle time.Duration
ExtraConditions []AuthCondition
LoggedInMessage string
LoginFailMessage string
UserData ResultRow
// contains filtered or unexported fields
}
AuthObject is a struct that holds all the information to perform a correct authentication against the user table in the database.
var Auth AuthObject
Auth is the authentication object
func (*AuthObject) CheckPasswordHash ¶
func (a *AuthObject) CheckPasswordHash(password, hash string) bool
CheckPasswordHash compares password and hash for Authentication using bcrypt.
func (*AuthObject) GetExpirationFromNow ¶
func (a *AuthObject) GetExpirationFromNow() time.Time
GetExpirationFromNow returns the expiration time from now.
func (*AuthObject) HashPassword ¶
func (a *AuthObject) HashPassword(password string) (string, error)
HashPassword create a password hash
func (*AuthObject) IsSessionExpired ¶
func (a *AuthObject) IsSessionExpired(r *http.Request) (bool, error)
IsSessionExpired checks authentication, get cookie value and check against user record in database
func (*AuthObject) KillAuthSession ¶
func (a *AuthObject) KillAuthSession(w http.ResponseWriter, r *http.Request) error
KillAuthSession kills the auth session by reseting the expiration time in user record in database
func (*AuthObject) TokenGenerator ¶
func (a *AuthObject) TokenGenerator() string
TokenGenerator is the random token generator
type Controller ¶
type Controller struct {
DB *sql.DB
Models map[string]*Model
TemplateCache map[string]TemplateObject
TemplateLayout string
TemplateHomePage string
UnderConstructionLayout string
UnderConstructionPage string
Options map[string]controllerOptions
Router *chi.Mux
Config *AppConfig
Functions template.FuncMap
IPRateLimiter *RateLimiter // Rate limit by IP
UserRateLimiter *RateLimiter // Rate limit by username
}
Controller is the controller struct, contains the models, the templates, the web layout, the home page, the under construction page the controller options for each route, the router itself and the config struct.
func (*Controller) AddTemplateData ¶
func (c *Controller) AddTemplateData(td TemplateData, r *http.Request) TemplateData
AddTemplateData adds data for templates, the data will be available in the view to build the web page before response.
func (*Controller) CreateTemplateCache ¶
func (c *Controller) CreateTemplateCache(homePageFileName string, layoutTemplateFileName string) error
CreateTemplateCache loads the template files and creates a cache of templates in controller.
func (*Controller) GetAuthObject ¶
func (c *Controller) GetAuthObject() *AuthObject
GetAuthObject return Authobject
func (*Controller) GetFunctions ¶ added in v1.0.99
func (c *Controller) GetFunctions() template.FuncMap
GetFunctions returns the function map from the controller
func (*Controller) GetLinuxUsername ¶ added in v1.2.5
func (c *Controller) GetLinuxUsername(r *http.Request) string
Get Linux username from session
func (*Controller) GetSession ¶
func (c *Controller) GetSession() *scs.SessionManager
GetSession return session manager
func (*Controller) GetTemplate ¶
func (c *Controller) GetTemplate(page string) (*template.Template, error)
GetTemplate return a single template from template cache
func (*Controller) GetUnderConstructionTemplate ¶
func (c *Controller) GetUnderConstructionTemplate(page string) (*template.Template, error)
GetUnderConstructionTemplate get the under construction page
func (*Controller) Initialize ¶
func (c *Controller) Initialize(db *sql.DB, cfg *AppConfig)
Initialize from this function we pass a pointer to db connection and a pointer to appconfig struct
func (*Controller) IsSessionLinuxAuth ¶ added in v1.2.5
func (c *Controller) IsSessionLinuxAuth(r *http.Request) bool
Check if session is Linux-authenticated
func (*Controller) RegisterAction ¶
func (c *Controller) RegisterAction(route ActionRouting, action Action, model *Model)
RegisterAction register controller action - route, next, action and model RegisterAction, RegisterAuthAction, RegisterCustomAction are the most important functions in the gomvc package all functions are responsible for processing requests and generating responses. RegisterAction is used to register one of the pre defined actions View, Create, Update, Delete
func (*Controller) RegisterAuthAction ¶
func (c *Controller) RegisterAuthAction(authURL string, nextURL string, model *Model, authObject AuthObject)
RegisterAuthAction register controller action - route, next, action and model is used to register the authentication actions
func (*Controller) RegisterAuthActionLinux ¶ added in v1.2.5
func (c *Controller) RegisterAuthActionLinux(authURL string, nextURL string, authObject AuthObject)
RegisterAuthActionLinux register controller action - route, next, action and model is used to register the authentication actions
func (*Controller) RegisterCustomAction ¶
func (c *Controller) RegisterCustomAction(route ActionRouting, method int, model *Model, f http.HandlerFunc)
RegisterCustomAction register controller action - route, next, action and model RegisterAction, RegisterAuthAction, RegisterCustomAction are the most important functions in the gomvc package all functions are responsible for processing requests and generating responses. RegisterCustomAction is used to register any custom action that doesn't fit the pre defined actions View, Create, Update, Delete
func (*Controller) View ¶
func (c *Controller) View(t *template.Template, td *TemplateData, w http.ResponseWriter, r *http.Request)
View provides a set of methods (e.g. render()) for rendering purpose.
type DatabaseConf ¶
type DatabaseConf struct {
Server string
Port int // Add this
Dbname string
Dbuser string
Dbpass string
UseTLS bool // Add this
}
DatabaseConf set MySql server address, database name, username and password
type FirewallInfo ¶ added in v1.2.5
FirewallInfo struct contains information about detected firewall
func CheckFirewall ¶ added in v1.2.5
func CheckFirewall(port int) FirewallInfo
CheckFirewall checks for firewall and provides port opening suggestions
This function detects the operating system and checks if a firewall is installed. If a firewall is detected, it provides helpful messages about opening the required port.
Parameters:
- port: The port number your application is using
Returns:
- FirewallInfo: Information about detected firewall and suggestions
type Model ¶
type Model struct {
DB *sql.DB
PKField string
TableName string
OrderString string
Fields []string
Labels map[string]string
Relations []Relation
DefaultQuery string
// contains filtered or unexported fields
}
Model is the model struct holding all the data and parameters for each model.
func (*Model) AddRelation ¶
func (m *Model) AddRelation(db *sql.DB, tableName string, PKField string, keys SQLKeyPair, join_type JoinType, result_style ResultStyle)
AddRelation Add Foreign table (model) and assign a relation to another model
func (*Model) AssignLabels ¶
AssignLabels function to assign human friendly Names/Labels to MySql fields
func (*Model) GetRecords ¶
GetRecords is function to execute a query against a table/model with filters (WHERE filters)
func (*Model) NewQueryBuilder ¶ added in v1.2.5
func (m *Model) NewQueryBuilder() *QueryBuilder
NewQueryBuilder creates a new query builder for a model
type QueryBuilder ¶ added in v1.2.5
type QueryBuilder struct {
// contains filtered or unexported fields
}
QueryBuilder provides a safe way to build complex queries
func (*QueryBuilder) Count ¶ added in v1.2.5
func (qb *QueryBuilder) Count() (int64, error)
Count returns the count of matching records
func (*QueryBuilder) Execute ¶ added in v1.2.5
func (qb *QueryBuilder) Execute() ([]ResultRow, error)
Execute executes the query and returns results
func (*QueryBuilder) First ¶ added in v1.2.5
func (qb *QueryBuilder) First() (ResultRow, error)
First executes the query and returns the first result
func (*QueryBuilder) GroupBy ¶ added in v1.2.5
func (qb *QueryBuilder) GroupBy(columns ...string) *QueryBuilder
GroupBy adds GROUP BY clause
func (*QueryBuilder) Join ¶ added in v1.2.5
func (qb *QueryBuilder) Join(foreignTable, foreignPK, localKey, foreignKey string) *QueryBuilder
Join adds an INNER JOIN
func (*QueryBuilder) LeftJoin ¶ added in v1.2.5
func (qb *QueryBuilder) LeftJoin(foreignTable, foreignPK, localKey, foreignKey string) *QueryBuilder
LeftJoin adds a LEFT JOIN
func (*QueryBuilder) Limit ¶ added in v1.2.5
func (qb *QueryBuilder) Limit(limit int64) *QueryBuilder
Limit sets the LIMIT
func (*QueryBuilder) Offset ¶ added in v1.2.5
func (qb *QueryBuilder) Offset(offset int64) *QueryBuilder
Offset sets the OFFSET
func (*QueryBuilder) OrWhere ¶ added in v1.2.5
func (qb *QueryBuilder) OrWhere(field, operator string, value interface{}) *QueryBuilder
OrWhere adds a WHERE condition with OR logic
func (*QueryBuilder) OrderBy ¶ added in v1.2.5
func (qb *QueryBuilder) OrderBy(column, direction string) *QueryBuilder
OrderBy adds ORDER BY clause
func (*QueryBuilder) Select ¶ added in v1.2.5
func (qb *QueryBuilder) Select(columns ...string) *QueryBuilder
Select specifies columns to select
func (*QueryBuilder) Where ¶ added in v1.2.5
func (qb *QueryBuilder) Where(field, operator string, value interface{}) *QueryBuilder
Where adds a WHERE condition with AND logic
func (*QueryBuilder) WhereIn ¶ added in v1.2.5
func (qb *QueryBuilder) WhereIn(field string, values []interface{}) *QueryBuilder
WhereIn adds a WHERE IN condition
type QueryType ¶
type QueryType string
QueryType the query type identifier type CRUD (Create, Read, Update, Delete)
type RateLimitConf ¶ added in v1.2.5
type RateLimitConf struct {
Enabled bool
IPMaxAttempts int
IPBlockMinutes int
UsernameMaxAttempts int
UsernameBlockMinutes int
}
RateLimitConf for rate limiting configuration
type RateLimiter ¶ added in v1.2.5
type RateLimiter struct {
// Configuration
MaxAttempts int // Max attempts before blocking
BlockDuration time.Duration // How long to block
CleanupPeriod time.Duration // How often to cleanup old records
// contains filtered or unexported fields
}
RateLimiter tracks failed login attempts
func NewRateLimiter ¶ added in v1.2.5
func NewRateLimiter(maxAttempts int, blockDuration time.Duration) *RateLimiter
NewRateLimiter creates a new rate limiter
func (*RateLimiter) GetBlockedUntil ¶ added in v1.2.5
func (rl *RateLimiter) GetBlockedUntil(identifier string) time.Time
GetBlockedUntil returns when the identifier will be unblocked
func (*RateLimiter) GetRemainingAttempts ¶ added in v1.2.5
func (rl *RateLimiter) GetRemainingAttempts(identifier string) int
GetRemainingAttempts returns how many attempts are left before blocking
func (*RateLimiter) GetStats ¶ added in v1.2.5
func (rl *RateLimiter) GetStats() map[string]interface{}
GetStats returns current rate limiter statistics
func (*RateLimiter) IsBlocked ¶ added in v1.2.5
func (rl *RateLimiter) IsBlocked(identifier string) bool
IsBlocked checks if an identifier (IP or username) is currently blocked
func (*RateLimiter) RecordFailedAttempt ¶ added in v1.2.5
func (rl *RateLimiter) RecordFailedAttempt(identifier string)
RecordFailedAttempt records a failed login attempt
func (*RateLimiter) ResetAttempts ¶ added in v1.2.5
func (rl *RateLimiter) ResetAttempts(identifier string)
ResetAttempts clears attempts for an identifier (on successful login)
type Relation ¶
type Relation struct {
Join SQLJoin
Foreign_model Model
ResultStyle ResultStyle
}
Relation is the relation to another table
type RequestObject ¶
type RequestObject struct {
// contains filtered or unexported fields
}
RequestObject is a struct builded from the http request, holds the url data in a convinient way.
type ResultRow ¶
type ResultRow struct {
Values []interface{}
Fields []string
Subresult []ResultRow
// contains filtered or unexported fields
}
ResultRow is the result coming from MySql database
func (*ResultRow) GetFieldIndex ¶
GetFieldIndex rerurns the field index using its name
type ResultStyle ¶
type ResultStyle int
ResultStyle, full dataset result from database OR dataset result with sub-result nested datasets
const ( ResultStyleFullresult ResultStyle = 0 ResultStyleSubresult ResultStyle = 1 )
type SQLField ¶
type SQLField struct {
FieldName string
Value interface{}
}
SQLField the MySql table field object
type SQLJoin ¶
type SQLJoin struct {
Foreign_table string
Foreign_PK string
KeyPair SQLKeyPair
Join_type JoinType
}
SQLJoin the type of MySql Join used by Relation
type SQLKeyPair ¶
SQLKeyPair local<->foreign key pair
type ServerConf ¶
ServerConf http listening port and true/false option for https
type TemplateData ¶
type TemplateData struct {
Auth AuthObject
AuthExpired bool
Model Model
Result []ResultRow
URLParams map[string][]interface{}
CustomValues map[string][]interface{}
CSRFToken string
Flash string
Warning string
Error string
PageName string
}
TemplateData is used to provide all data to the template engine to build the webpage.
type TemplateObject ¶
type TemplateObject struct {
// contains filtered or unexported fields
}
TemplateObject is the template struct, holds the filename and the template object.