Wheel Doc

Internals

1  Overview

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.

2  Model

var Db

var Db *gorm.DB
          

Global var to access database.

var Errors

var Errors []string
          

Global var to return errors when creating or updating data.

type Query

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
          
func Connect

func Connect()
          

Connects to database properly configured in file config/database.yml.

func Disconnect

func Disconnect()
          

Disconnects from database.

func TableName

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

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

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

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

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.

2.1  Search Engine

func (q *Query) SearchEngine

func (q *Query) SearchEngine(criteria map[string]string))
          

Builds the query to filter records of an specific table in the database.

func Criteria

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"}
          

2.2  Pagination

func (q *Query) Pagination

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.

2.3  Ordering

func (q *Query) Ordering

func (q *Query) Ordering(order string) 
          

Builds query for ordering. Be sure to sanitize the order parameter to avoid SQL injection.

3  View

type SystemMessage struct

type SystemMessage struct {
  Type    string `json:"type"`
  Content string `json:"content"`
}
          

Basic message as JSON.

  • type: can be alert to announce error/danger or notice to announce success.
  • content: is the full explanation of the message.
type DefaultMessage struct

type DefaultMessage struct {
  Message SystemMessage `json:"system_message"`
}
          

Wrap for SystemMessage. Example:


{
    "system_message": {
        "type": "notice",
        "content": "product was successfully created"
    }
}
          
type ErrorMessage struct

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

type MainPagination struct {
  CurrentPage  int `json:"current_page"`
  TotalPages   int `json:"total_pages"`
  TotalEntries int `json:"total_entries"`
}
          

Pagination data for lists.

func SetSystemMessage

func SetSystemMessage(mType string, content string) SystemMessage
          

Defines a SystemMessage.

func SetDefaultMessage

func SetDefaultMessage(mType string, content string) DefaultMessage  
          

Defines a DefaultMessage.

func SetErrorMessage

func SetErrorMessage(mType string, content string, errs []error) ErrorMessage
          

Defines an ErrorMessage.

func SetUnauthorizedErrorMessage

func SetUnauthorizedErrorMessage() DefaultMessage
          

Returns Unauthorized HTTP error message.


{
    "system_message": {
        "type": "alert",
        "content": "401 Unauthorized"
    }
}
          
func SetForbiddenErrorMessage

func SetForbiddenErrorMessage() DefaultMessage
          

Returns Forbidden HTTP error message.


{
    "system_message": {
        "type": "alert",
        "content": "403 Forbidden"
    }
}
          
func SetNotFoundErrorMessage

func SetNotFoundErrorMessage() DefaultMessage 
          

Returns Not Found HTTP error message.


{
    "system_message": {
        "type": "alert",
        "content": "404 Not Found"
    }
}
          

4  Handler (Controller)

func ApiRoot

func ApiRoot(w http.ResponseWriter, r *http.Request)
          

Responds to an HTTP request, as JSON, for the URL "/"

func Error401

func Error401(w http.ResponseWriter, r *http.Request)
          

Responds to a HTTP request, as JSON, when unauthorized error happens.

func Error403

func Error403(w http.ResponseWriter, r *http.Request)
          

Responds to a HTTP request, as JSON, when forbidden error happens.

func Error404

func Error404(w http.ResponseWriter, r *http.Request)
          

Responds to a HTTP request, as JSON, when not found error happens.

func QueryParamsToMapCriteria

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

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

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

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)
          

5  Config

type AppConfig

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

var App AppConfig
          

Variable that holds the application configuration.

6  Others

6.1  Log

var Debug, var info, var Warn, var Error and var Fatal

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
          

6.2  Mailer

func SetFrom

func SetFrom(name string, tEmail string)
          

Sets e-mail: from field.

func AddTo

func AddTo(name string, tEmail string)
          

Adds receipts in e-mail to field.

func AddCc

func AddCc(name string, tEmail string)
          

Adds receipts in e-mail cc field.

func AddBcc

func AddBcc(name string, tEmail string)
          

Adds receipts in e-mail bcc field.

func Receipts

func Receipts() []string
          

Returns a list of receipts.

func ResetReceipts

func ResetReceipts()
          

Removes all receipts.

func Send

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.

6.3  Internationalization (I18n)

type Keys

type Keys struct {
  Welcome                      string `yaml:"welcome"`
  PasswordRecoveryInstructions string `yaml:"password_recovery_instructions"`
}
          

Structure that holds data locale.

var I18n

var I18n Keys
          

Variable that holds data locale.

func Load

func Load(locale string)
          

Loads locale. This is mostly used for load user's locales.

6.4  Crypto

func SetPassword

func SetPassword(password string) string
          

Returns an asymmetrically encrypted string.

func CheckPassword

func CheckPassword(password string, hashedPassword string) bool
          

Encrypts the password parameter and checks it with the hashedPassword parameter.

func RandString

func RandString(size int) string
          

Returns random strings. The length of the string is defined by the size paramenter.

func EncryptText

func EncryptText(clearText string, key string) string
          

Encrypts a string symmetrically.

6.5  Conversor

func StringToInterface

func StringToInterface(contentType string, contentValue string) (interface{}, error)
          

Converts string to interface.

func StringToInt

func StringToInt(valueContent string) (interface{}, error)
          

Converts string to integer.

func StringToFloat

func StringToFloat(valueContent string) (interface{}, error) 
          

Converts string to float.

func StringToBoolean

func StringToBoolean(valueContent string) (interface{}, error)
          

Converts string to boolean.