ghost

package
v0.0.0-...-7e476e1 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2017 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ContentTypeHTML = `text/html; charset=utf-8`
	ContentTypeJSON = `application/json; charset=utf-8`
	ContentTypeJS   = `application/javascript`
	ContentTypeCSS  = `text/css`
)
View Source
const (
	SQLToFindUserByEmail = `SELECT id from users WHERE email = '%s';`
	SQLToGetUsersRole    = `SELECT role from users WHERE id = '%s';`

	//General
	//NO SEMI COLONS AT THE END
	SQLToSelectAllFieldsFrom = `SELECT * FROM %s.%s`
	SQLToSelectWhere         = `SELECT * FROM %s.%s WHERE id = '%v'` //depracated
	SQLToSelectByID          = `SELECT * FROM %s.%s WHERE id = '%v'`
	SQLToSelectWhereXEqualsY = `SELECT * FROM %s.%s WHERE %s = '%v'`

	SQLToInsertReturningJSON            = `INSERT INTO %s.%s(%s) VALUES (%s) returning row_to_json(%s)`
	SQLToInsertAllDefaultsReturningJSON = `INSERT INTO %s.%s DEFAULT VALUES returning row_to_json(%s)`
	SQLToDeleteWhere                    = `DELETE FROM %s.%s WHERE id = '%v'`
	SQLToUpdateWhereReturningJSON       = `UPDATE %s.%s SET (%s) = (%s) WHERE id = '%v' returning row_to_json(%s)`

	//Full text search_path
	SQLToFullTextSearch = `` /* 174-byte string literal not displayed */
)

SQl query strings for application-wide use

Variables

View Source
var (
	SuperUserDBConfig  dbConfig
	ServerUserDBConfig dbConfig
)

SuperUserDBConfig is the connection configuration for the super user ServerUserDBConfig is the connection configuration for the 'server' role user

View Source
var App application

App is the container for the app-wide constructs like database, router and mailserver

View Source
var BeforeServe func()

ActivatePackages is a hook for activating packages from main

View Source
var Defaults = config{

	PgSuperUser:  "postgres",
	PgDBName:     "testdb",
	PgPort:       "5432",
	PgServer:     "localhost",
	PgDisableSSL: true,

	ApiPort:  "3000",
	JWTRealm: "Your App Name",
	Host:     "localhost",
	Protocol: "http",

	ActivateEmail: false,
	SmtpHost:      "smtp",
	SmtpPort:      "25",
	SmtpUserName:  "info@yourdomain.com",
	SmtpFrom:      "info@yourdomain.com",
	EmailFrom:     "Your Name",

	BundlesInstalled: make([]string, 0, 0),

	GlobalMiddleware: []string{"RequestID", "RealIP", "Logger", "Recoverer", "CloseNotify", "Timeout"},
	Timeout:          60,

	ActivateCors:         false,
	CorsAllowedOrigins:   []string{"*"},
	CorsAllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "SEARCH"},
	CorsAllowedHeaders:   []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
	CorsExposedHeaders:   []string{"Link"},
	CorsAllowCredentials: true,
	CorsMaxAge:           300,
}

Defaults the the app wide default settings

View Source
var ServeCmd = &cobra.Command{
	Use:   "serve",
	Short: "Starts the ghost server",
	Long:  `Start the ghost API Server`,
	RunE:  serve,
}

ServeCmd represents the serve command

View Source
var TestDBConfig = dbConfig{
	// contains filtered or unexported fields
}

TestDBConfig is a ready to go database config for testing purposes TODO: at the moment the config for testing is fixed - need to work out clean way of allowing users to specify different config

Functions

func AddRecordToContext

func AddRecordToContext(next http.Handler) http.Handler

func AddSchemaAndTableToContext

func AddSchemaAndTableToContext(next http.Handler) http.Handler

func AllOK

func AllOK(oks ...bool) bool

AllOK Takes any number of bools and returns true if all are true, or false if ANY are false

func AskForConfirmation

func AskForConfirmation(s string) bool

AskForConfirmation asks the user for confirmation. A user must type in "yes" or "no" and then press enter. It has fuzzy matching, so "y", "Y", "yes", "YES", and "Yes" all count as confirmations. If the input is not recognized, it will ask again. The function does not return until it gets a valid response from the user.

func CreateDefaultConfigFile

func CreateDefaultConfigFile(configFileName string) error

createDafaultConfigFile creates the default config.json template with sane defaults TODO: Will overwrite existing config.json, so ask for confirmation

func DBErrorCodeToHTTPErrorCode

func DBErrorCodeToHTTPErrorCode(dbCode pq.ErrorCode) (httpCode int)

DBErrorCodeToHTTPErrorCode is a helper to translate error codes from the database into meaningful HTTP codes

func HyphensToUnderscores

func HyphensToUnderscores(table string) string

HyphensToUnderscores replaces all hyphens in the string with underscores. This is so you can use pretty URLs with hyphens (as recommended by Google) whilst still using underscores in App.DB table names - which means they don't have to be quoted all the time https://support.google.com/webmasters/answer/76329?hl=en

func Log

func Log(module string, isOk bool, message string, err error)

Log outputs a custom ghost log entry

func LogDebug

func LogDebug(module string, isOk bool, message string, err error)

LogDebug outputs a custom ghost log entry if debugmode is on

func LogFatal

func LogFatal(module string, isOk bool, message string, err error)

LogFatal outputs a custom ghost log entry and exits

func MapToValsAndCols

func MapToValsAndCols(r map[string]interface{}) (cols, vals string)

MapToValsAndCols iterates over the map resulting from binding a JSON request body and creates cols and vals strings to be used in SQL query

func RandomString

func RandomString(strlen int) string

RandomString generates a random string of int length

func TestErrorFatal

func TestErrorFatal(t *testing.T, description string, got string, expected string)

Types

type Bundles

type Bundles []string

type Query

type Query struct {
	//userQueryString is for when you need to provide complete, preformed SQL
	//This option will override any BaseAQL + args
	OverrideQueryString string
	//BaseSQL is a formatted SQL string with placeholder for SQLArgs
	BaseSQL string
	//SQLArgs are inserted into the BaseSQL in the order they appear
	SQLArgs []interface{}
	//SELECT fields
	Select []string
	//From Schema.Table
	Schema, Table string
	//Where
	Where []WhereConfig
	//Indicate whether to rquest JSON array or object
	//and when unmarshalling, whether map or slice of maps
	IsList bool
	//Role to execute the query as
	Role string
	//UserID to set on the query context
	UserID string
	//CacheLevel specifies the level of caching to use: all, role, user
	//Omitting, or using any other value, will bypass caching
	CacheLevel string

	//CacheExpiry
	CacheExpiry int
	// contains filtered or unexported fields
}

Query is the basic building block of an SQL query

func (*Query) Build

func (q *Query) Build() error

Build runs a query against the data store and returns JSON

type ResponseError

type ResponseError struct {
	HTTPCode     int          `json:"httpCode"`
	DBErrorCode  pq.ErrorCode `json:"dbCode"`
	ErrorMessage string       `json:"message"`
	Schema       string       `json:"schema"`
	Table        string       `json:"table"`
	Record       string       `json:"record"`
}

ResponseError is the struct containing details of a server error

type WhereConfig

type WhereConfig struct {
	Key        string
	Operator   string
	Value      interface{}
	AnyValue   []interface{}
	JoinWithOr bool
}

WhereConfig describes one or more where clauses

Jump to

Keyboard shortcuts

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