In this section you will find the documentation for internal functions. When you generate a new API or CRUD if you read the generated code you will face these functions below. Here, you can learn more about them.
var Db *gorm.DB
Global var to access database.
var Errors []string
Global var to return errors when creating or updating data.
type Query struct {
Db *gorm.DB
Table interface{}
}
Structure used to build advanced queries, such as Search Engine, Pagination and Ordering. See this full example below:
var people []entities.Person
var person entities.Person
q := model.Query{Db: model.Db, Table: &person}
q.SearchEngine(criteria)
q.Ordering(order)
currentPage, totalPages, totalEntries := q.Pagination(page, perPage)
q.Db.Find(&people)
return people, currentPage, totalPages, totalEntries
Quick tip!
At the example above, we are using SearchEngine, Pagination and Ordering together. But they are independent from each other, so feel free to use them individually.
func Connect()
Connects to database properly configured in file config/database.yml.
func Disconnect()
Disconnects from database.
func TableName(table interface{}) string
Returns the name of the table in database as string.
The parameter table is an entity. You can check all available entities in directory db/entities/.
tableName := model.TableName(entities.User)
log.Info.Println(tableName)
The example above will print:
[INFO] users
func GetColumnType(table interface{}, columnName string) (string, error)
Returns the type of any column from a table as string.
The parameter table is an entity. You can check all available entities in directory db/entities/.
columnType := model.GetColumnType(entities.User, 'email')
log.Info.Println(columnType)
The example above will print:
[INFO] string
func GetColumnValue(table interface{}, columnName string) (interface{}, error)
Returns the value of any column from a table as interface{}.
The parameter table is an entity. You can check all available entities in directory db/entities/.
func SetColumnValue(table interface{}, columnName string, value string) error
Sets a value to a column of a specific table.
The parameter table is an entity. You can check all available entities in directory db/entities/.
The parameter value is a string type, even if you are setting a value to a non-string column. Don't worry, this function will convert properly the value to the type of the column.
func ColumnsFromTable(table interface{}, all bool) []string
Returns an array of strings with all columns and relationships of the table in the database.
The parameter table is an entity. You can check all available entities in directory db/entities/.
The parameter all is a boolean. If setted as true, returns all columns and relationships. If setted as false, returns all columns only.
func (q *Query) SearchEngine(criteria map[string]string))
Builds the query to filter records of an specific table in the database.
Quick tip!
If you have missed the explanation of the q *Query paramenter, please. check it.
func Criteria(table interface{}, criteria map[string]string, logic string) (string, []interface{})
Extract the criteria parameter and tranformt it as SQL prepared statements (string) and pushes the values into an array of interfaces. This function is called internally by the SeachEngine function.
The parameter logic you can use AND ou OR in your query.
var m map[string]string
m = make(map[string]string)
m["name_cont"] = "a"
m["email_end"] = "com"
s, i := searchengine.Criteria(entities.User, m, "AND")
log.Info.Println(s)
log.Info.Println(i)
The example above will print:
[INFO] name ILIKE ? AND email ILIKE ? [INFO] {"%a%" "%com"}
func (q *Query) Pagination(page interface{}, perPage interface{}) (int, int, int)
Builds query for pagination, setting the offset and limit. Parameters are the target page (as interface{}) and amount of items per page. It returns the current page (as int), total of pages and total of entries.
func (q *Query) Ordering(order string)
Builds query for ordering. Be sure to sanitize the order parameter to avoid SQL injection.
type SystemMessage struct {
Type string `json:"type"`
Content string `json:"content"`
}
Basic message as JSON.
type DefaultMessage struct {
Message SystemMessage `json:"system_message"`
}
Wrap for SystemMessage. Example:
{
"system_message": {
"type": "notice",
"content": "product was successfully created"
}
}
type ErrorMessage struct {
Message SystemMessage `json:"system_message"`
Errors []string `json:"errors"`
}
Wrap for SystemMessage with an array of errors. Each error as string. Example:
{
"system_message": {
"type": "alert",
"content": "product was not created",
},
"errors": [
"name can't be blank",
"price can't be blank",
...
]
}
type MainPagination struct {
CurrentPage int `json:"current_page"`
TotalPages int `json:"total_pages"`
TotalEntries int `json:"total_entries"`
}
Pagination data for lists.
func SetSystemMessage(mType string, content string) SystemMessage
Defines a SystemMessage.
func SetDefaultMessage(mType string, content string) DefaultMessage
Defines a DefaultMessage.
func SetErrorMessage(mType string, content string, errs []error) ErrorMessage
Defines an ErrorMessage.
func SetUnauthorizedErrorMessage() DefaultMessage
Returns Unauthorized HTTP error message.
{
"system_message": {
"type": "alert",
"content": "401 Unauthorized"
}
}
func SetForbiddenErrorMessage() DefaultMessage
Returns Forbidden HTTP error message.
{
"system_message": {
"type": "alert",
"content": "403 Forbidden"
}
}
func SetNotFoundErrorMessage() DefaultMessage
Returns Not Found HTTP error message.
{
"system_message": {
"type": "alert",
"content": "404 Not Found"
}
}
func ApiRoot(w http.ResponseWriter, r *http.Request)
Responds to an HTTP request, as JSON, for the URL "/"
func Error401(w http.ResponseWriter, r *http.Request)
Responds to a HTTP request, as JSON, when unauthorized error happens.
func Error403(w http.ResponseWriter, r *http.Request)
Responds to a HTTP request, as JSON, when forbidden error happens.
func Error404(w http.ResponseWriter, r *http.Request)
Responds to a HTTP request, as JSON, when not found error happens.
func QueryParamsToMapCriteria(param string, mapParams map[string][]string) map[string]string
Translates the HTTP parameter search to a simple map structure for SearchEngine use. Example:
http://localhost:8081/people?search[name_cont]=A&search[age_gt]=21
It will transform the parameter search to:
map[string]string{ "name_cont" : "A", "age_gt" : "21" }
func SetPermittedParamsToEntity(params interface{}, entity interface{})
Sets data to an Entity struct from a Permitted Params struct to avoid Mass Assignment vulnerability.
....
type UserPermittedParams struct {
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"password"`
Locale string `json:"locale"`
Admin bool `json:"admin"`
}
func UserCreate(w http.ResponseWriter, r *http.Request) {
var newUser = entities.User{}
log.Info.Println("Handler: UserCreate")
w.Header().Set("Content-Type", "application/json")
var userParams UserPermittedParams
_ = json.NewDecoder(r.Body).Decode(&userParams)
handler.SetPermittedParamsToEntity(&userParams, &newUser)
valid, errs := user.Create(&newUser)
if valid {
json.NewEncoder(w).Encode(user.SuccessfullySavedJson{SystemMessage: view.SetSystemMessage("notice", "user was successfully created"), User: user.SetJson(newUser)})
} else {
json.NewEncoder(w).Encode(view.SetErrorMessage("alert", "user was not created", errs))
}
}
....
func SetPermittedParamsToEntityWithExceptions(params interface{}, entity interface{}, excepts []string)
It does the same as SetPermittedParamsToEntity, but you can set a list of params to remove from permitted list.
paramsExcept := []string{"Password"}
handler.SetPermittedParamsToEntityWithExceptions(&userParams, &userNew, paramsExcept)
func SetPermittedParamsToEntityButOnly(params interface{}, entity interface{}, only []string)
It does the same as SetPermittedParamsToEntity, but you can set a sublist of permitted params.
paramsOnly := []string{"Password"}
handler.SetPermittedParamsToEntityButOnly(&userParams, &userNew, paramsOnly)
type AppConfig struct {
AppName string `yaml:"app_name"`
AppRepository string `yaml:"app_repository"`
SecretKey string `yaml:"secret_key"`
ResetPasswordExpirationSeconds int `yaml:"reset_password_expiration_seconds"`
ResetPasswordUrl string `yaml:"reset_password_url"`
TokenExpirationSeconds int `yaml:"token_expiration_seconds"`
Locales []string `yaml:"locales"`
}
Structure that holds the application configuration.
var App AppConfig
Variable that holds the application configuration.
var (
Debug = log.New(writer, fmt.Sprintf("\033[94m[DEBUG]\033[39m "), log.LstdFlags)
Info = log.New(writer, fmt.Sprintf("\033[36m[INFO]\033[39m "), log.LstdFlags)
Warn = log.New(writer, fmt.Sprintf("\033[93m[WARN]\033[39m "), log.LstdFlags)
Error = log.New(writer, fmt.Sprintf("\033[91m[ERROR]\033[39m "), log.LstdFlags)
Fatal = log.New(writer, fmt.Sprintf("\033[90m[FATAL]\033[39m "), log.LstdFlags)
)
Variables for log data. Usage:
log.Debug.Println("Log a debug")
log.Info.Println("Log an info")
log.Warn.Println("Log an warn")
log.Error.Println("Log an error")
The example above will print:
[DEBUG] Log a debug [INFO] Log an info [WARN] Log an warn [ERROR] Log an error
func SetFrom(name string, tEmail string)
Sets e-mail: from field.
func AddTo(name string, tEmail string)
Adds receipts in e-mail to field.
func AddCc(name string, tEmail string)
Adds receipts in e-mail cc field.
func AddBcc(name string, tEmail string)
Adds receipts in e-mail bcc field.
func Receipts() []string
Returns a list of receipts.
func ResetReceipts()
Removes all receipts.
func Send(subject string, body string, html bool)
Sends e-mail. The parameter html when true send email in HTML else sends e-mail in plain text.
type Keys struct {
Welcome string `yaml:"welcome"`
PasswordRecoveryInstructions string `yaml:"password_recovery_instructions"`
}
Structure that holds data locale.
var I18n Keys
Variable that holds data locale.
func Load(locale string)
Loads locale. This is mostly used for load user's locales.
Quick tip!
Check the feature Internationalization (I18n) session to learn how to add new locales.
func SetPassword(password string) string
Returns an asymmetrically encrypted string.
func CheckPassword(password string, hashedPassword string) bool
Encrypts the password parameter and checks it with the hashedPassword parameter.
func RandString(size int) string
Returns random strings. The length of the string is defined by the size paramenter.
func EncryptText(clearText string, key string) string
Encrypts a string symmetrically.
func StringToInterface(contentType string, contentValue string) (interface{}, error)
Converts string to interface.
func StringToInt(valueContent string) (interface{}, error)
Converts string to integer.
func StringToFloat(valueContent string) (interface{}, error)
Converts string to float.
func StringToBoolean(valueContent string) (interface{}, error)
Converts string to boolean.