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
Index ¶
- Constants
- Variables
- func BuildQuery(queryType QueryType, fields []SQLField, table SQLTable, joins []SQLJoin, ...) (string, []interface{})
- func ConnectDatabase(user string, pass string, dbname string) (*sql.DB, error)
- func FindInSlice(slice []string, value string) 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) 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) RegisterAction(route ActionRouting, action Action, model *Model)
- func (c *Controller) RegisterAuthAction(authURL string, nextURL string, model *Model, 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 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) Instance() Model
- func (m *Model) Label(field string) string
- func (m *Model) Save(fields []SQLField) (bool, error)
- func (m *Model) Update(fields []SQLField, id string) (bool, error)
- type QueryType
- 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 quey func
func ConnectDatabase ¶
ConnectDatabase
func FindInSlice ¶
FindInSlice find a value in a slice and return the index
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 }
func ReadConfig ¶
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 // 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 }
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) 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) 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) 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 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 }
func (*Model) AddRelation ¶
func (m *Model) AddRelation(db *sql.DB, tableName string, PKField string, keys SQLKeyPair, join_type JoinType, result_style ResultStyle)
Add Foreign table (model)
func (*Model) AssignLabels ¶
func (*Model) GetRecords ¶
Query table with filters
type Relation ¶
type Relation struct { Join SQLJoin Foreign_model Model ResultStyle ResultStyle }
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 }
func (*ResultRow) GetFieldIndex ¶
type ResultStyle ¶
type ResultStyle int
const ( ResultStyleFullresult ResultStyle = 0 ResultStyleSubresult ResultStyle = 1 )
type SQLJoin ¶
type SQLJoin struct { Foreign_table string Foreign_PK string KeyPair SQLKeyPair Join_type JoinType }
type SQLKeyPair ¶
type ServerConf ¶
type TemplateData ¶
type TemplateData struct { Model Model Result []ResultRow URLParams map[string][]interface{} CustomValues map[string][]interface{} CSRFToken string Flash string Warning string Error 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.