ymux

package
Version: v0.1.43 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2021 License: BSD-3-Clause Imports: 55 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DB *sql.DB
View Source
var Db8_rr = false
View Source
var Db8_vd = false
View Source
var DbFlag = make(map[string]bool)
View Source
var DbType = "Postgres" // var DbType = "SQLite"
View Source
var DefaultServeMux = &defaultServeMux

DefaultServeMux is the default ServeMux used by Serve.

View Source
var FirstRequest bool = true
View Source
var LastResut []byte
View Source
var MuxMatchTypeMap = map[string]MuxMatchType{
	"MuxMatchTypeError":     MuxMatchTypeError,
	"MuxMatchTypeString":    MuxMatchTypeString,
	"MuxMatchTypeNumber":    MuxMatchTypeNumber,
	"MuxMatchTypeText":      MuxMatchTypeText,
	"MuxMatchTypeRE":        MuxMatchTypeRE,
	"MuxMatchTypeFunc":      MuxMatchTypeFunc,
	"MuxMatchTypeAnyString": MuxMatchTypeAnyString,
	"MuxMatchTypeUUID":      MuxMatchTypeUUID,
	"MuxMatchTypeBoolean":   MuxMatchTypeBoolean,
	"MuxMatchTypeHexNumber": MuxMatchTypeHexNumber,
	"MuxMatchTypeLen":       MuxMatchTypeLen,
	"MuxMatchTypeEndRest":   MuxMatchTypeEndRest,
}
View Source
var PrePostTab = map[string]PrePostFx{
	"conv_qr_id":       ConvQrId,
	"conv_qr_id60":     ConvQrId60,
	"conv_geolocation": ConvGeolocation,
	"flush_priv_cache": PPFlushPrivCache,
}
View Source
var PwCache = "./pw-cache/%s/%s"

Plan - cache the password response - if it is older than 90 days, then discard and re-ask. Use first 4 of hash as a directory, then rest as file.

View Source
var QueryConfig = []CrudQueryConfig{}
View Source
var SaveValueMux *sync.Mutex
View Source
var StoredProcConfig = []CrudStoredProcConfig{}
View Source
var TableConfig = []CrudConfig{}

Table based end points

View Source
var ThisEpoc int
View Source
var TimeRemain int
View Source
var UploadPath string

Functions

func AbsFloat64

func AbsFloat64(a float64) float64

AbsFloat64 returns the absolute value. Negatives are converted to positive.

func AddMatchFunc

func AddMatchFunc(name string, fx MatchFunc)

func AddToPrePostTab

func AddToPrePostTab(name string, fx PrePostFx)

func AddValidationFunction

func AddValidationFunction(name string, fx ValidationFunction)

AddValidationFunction will add a new (or replace an existing) named validation. The default validations are email and us_zip.

func AppendBulkConfig

func AppendBulkConfig(BulkConfig CrudBulkConfig)

ymux.AppendBulkConfig(BulkConfig)

func AppendConfig

func AppendConfig(sp []CrudStoredProcConfig, tp []CrudConfig, qp []CrudQueryConfig)

func Assert

func Assert(b bool)

Assert assumes that 'b' is true - if not the program will fail and exit.

func BindFixer

func BindFixer(stmt string, vars []interface{}) (modStmt string, modVars []interface{}, names []string)

Convert from Postgres $1, ... $n to

SQLite 	- ?, ?, ? - with positional replacement
MySql 	- ?, ?, ? - with positional replacement
MariaDB 	- ?, ?, ? - with positional replacement
Oracle 	- :n0, :n1, :n2 - named and return names.

func BoolToYesNo

func BoolToYesNo(b bool) string

BoolToYesNo convers a boolena to a Yes/No value.

func CallStoredProc

func CallStoredProc(DB *sql.DB, name string, args ...interface{}) (rv map[string]interface{}, raw string, err error)

func CheckJQueryHeaders

func CheckJQueryHeaders(www http.ResponseWriter, req *http.Request) (err error)

if e0 := ymux.CheckJQueryHeaders(www, req); e0 != nil {

func CheckPassword

func CheckPassword(pw string, db_flag map[string]bool, ignore bool) bool

CheckPassword if ignore is false will use remote site to validate passwrod. ighore should be true for things like the old password when chaning passwrods (so you can upgrade a password).

Documented: https://haveibeenpwned.com/API/v2#PwnedPasswords GET https://api.pwnedpasswords.com/range/{first 5 hash chars}

func CheckPriv

func CheckPriv(auth_token, user_id, needs_priv string) (rv bool)

Cacheing Funciton that checks privilages in Go Code.

func CheckTable

func CheckTable(DbSchema, TableName string) (err error)

func CleanPath

func CleanPath(p string) string

CleanPath returns the canonical path for p, eliminating . and .. elements.

func CleanupValue

func CleanupValue(www http.ResponseWriter, req *http.Request)

func ConnectToPG

func ConnectToPG(gCfg *BaseConfigType) *sql.DB

ConnectToPG Connects to the postgresDB. This can be called multiple times.

func Contains

func Contains(lookFor, has []string) (missing []string, allFound bool)

func ConvertDataToImage

func ConvertDataToImage(data, fn string) (err error)

ConvertDataToImage takes a data:image and converts it to a file. TODO

if image/png -> add .png
if image/jpg -> add .jpg
if image/svg -> add .svg

func CsvUnmarshal

func CsvUnmarshal(in string) (rv []map[string]string, colNames []string, err error)

func DebugFlagProcess

func DebugFlagProcess(DbFlag *string, db_flag map[string]bool, gCfg *BaseConfigType)

func LiveMonSetup(name string, db_flag map[string]bool, gCfg *BaseConfigType) {

func DecryptText

func DecryptText(key, text []byte) ([]byte, error)

func DumpStoredProcDefs

func DumpStoredProcDefs()

func EncodeBase36

func EncodeBase36(idBase36 string) (idOut string, err error)

func EncodeFromBase10to36

func EncodeFromBase10to36(idBase10 string) (idOut string, err error)

func EncodeMuxMatchTypeToString

func EncodeMuxMatchTypeToString(ww MuxMatchType) (ss string)

func EncryptText

func EncryptText(key, text []byte) ([]byte, error)

func EncryptTextIndexable

func EncryptTextIndexable(key, xiv, text []byte) ([]byte, error)

func EncryptTextToB64

func EncryptTextToB64(key, text []byte) string

func EncryptTextToB64Indexable

func EncryptTextToB64Indexable(key, iv, text []byte) string

func ErrorReturn

func ErrorReturn(www http.ResponseWriter, req *http.Request, logFilePtr *os.File, reqErr RequestError)

func ErrorReturnGoRoutine

func ErrorReturnGoRoutine(www http.ResponseWriter, req *http.Request, logFilePtr *os.File, reqErr RequestError)

func ExcelUnmarshal

func ExcelUnmarshal(excelFileName string, sheetIndex int) (rv []map[string]string, err error)

func ExecuteATemplateByName

func ExecuteATemplateByName(tmpl, tmplName string, data interface{}) (rv string)

func ExecuteATemplateByNameWithError

func ExecuteATemplateByNameWithError(tmpl, tmplName, tmplIfNotFound string, data interface{}) (rv string, err error)

ExecuteATemplateByNameWithError parses tmpl as a set of tempaltes and will run tmplName if it in the set of templates. If tmplName is not found and if tmplIfNotFOund is the name of a template (Pass "" if not used) then it will run this backup/default template. The data for the template run is 'data'. The resulting string is returned or an error.

func FindDataType

func FindDataType(colName string, colTypes []CrudColTypeData) (dt string, found bool)

if dt, found := FindDataType(colName, colTypes); found {

func FlushPrivCache

func FlushPrivCache()

This will flush the cache whever a role/priv change takes place.

func FormatBool

func FormatBool(b bool) (s string)

func FoundCol

func FoundCol(www http.ResponseWriter, req *http.Request, WhereCols []string) (cols []string, colsData []interface{}, found bool)

cols, colsData, found := FoundCol ( www, req, CrudData.WhereCols )

func GenBindArray

func GenBindArray(Bind []string, gdata map[string]interface{}, row map[string]string) (inputData []interface{}, needBind bool)

inputData, needBind := GenBindArray(gd.Bind, gdata)

func GenOrderBy

func GenOrderBy(www http.ResponseWriter, req *http.Request, CrudData CrudConfig, posInTable int, gCfg *BaseConfigType) (rv string, err error)

xyzzy5050 - TODO - Add order by info? // check 'val' to be a valid order by column name xyzzy5050 - TODO - need to test this xyzzy5050 - TODO - need document format for __order_by__

a, b
a, -b
1, -b etc.
1 asc, b desc etc.
1 asc, "b" desc etc.

xyzzy5050 - TODO - add this to "view-query" pre defined??? - if so how xyzzy5050 - TODO - JSON format for this [c1,c2,...] - then just parse JSON strings xyzzy5050 - TODO - __where__=[{"col":"name","op":,"val":}] => ["col":"name","ord":"asc|desc"]

func GenProjected

func GenProjected(ProjectedCols []string) (rv string)

func GenQryFromCli

func GenQryFromCli() (rv string)

func GenRandBytesOracle

func GenRandBytesOracle() (buf []byte, ttl, epoc int, err error)

func GenUUID

func GenUUID() string

func GenWhere

func GenWhere(cols []string) string

GenWhere(cols)

func GeneralSetup

func GeneralSetup(gg *BaseConfigType)

func GenerateCallStoredProc

func GenerateCallStoredProc(filename, pkgName string)

func GetAllStoredProcNames

func GetAllStoredProcNames() (rv []string)

func GetAuthToVerify

func GetAuthToVerify(www http.ResponseWriter, req *http.Request) (TokToVerify string)

func GetBearer

func GetBearer(www http.ResponseWriter, req *http.Request, db_flag map[string]bool) (rv string)

GetBerrer use an authorization token, a cookie or a URL paramter to retreive the JWT berrer token.

func GetColumnMap

func GetColumnMap(DbSchema, TableName string) (cm map[string]bool, err error)

func GetDB

func GetDB() *sql.DB

Return connection to database.

func GetInsertNames

func GetInsertNames(www http.ResponseWriter, req *http.Request, potentialCols []string, pkCol string, colTypes []CrudColTypeData) (cols, vals string, inputData []interface{}, id string, err error)

GetInsertNames returns the list of columns for an insert, the list of placeholders for PG substitution of values, the list of values, the primary key or an error.

func GetInsertNamesMulti

func GetInsertNamesMulti(www http.ResponseWriter, req *http.Request, pos int, aMd map[string]string, potentialCols []string, pkCol string) (
	cols, vals string, inputData []interface{}, id string, err error,
)

cols, vals, inputData, id, err := GetInsertNamesMulti(www, req, ii, aMd, CrudData.InsertCols, CrudData.InsertPkCol)

func GetNameList

func GetNameList(www http.ResponseWriter, req *http.Request) (names []string)

func GetNameListFromSave

func GetNameListFromSave(www http.ResponseWriter, req *http.Request) (names []string)

func GetQueryNames

func GetQueryNames(www http.ResponseWriter, req *http.Request, potentialCols []ParamListItem, StoredProcdureName, URIPath string) (inputData []interface{}, err error)

func GetStoredProcNames

func GetStoredProcNames(www http.ResponseWriter, req *http.Request, potentialCols []ParamListItem, StoredProcdureName, URIPath string) (vals string, inputData []interface{}, err error)
   type ParamListItem struct {
   	ReqVar    string // variable for GetVar()
   	ParamName string // Name of variable (Info Only)
   	AutoGen   bool
	Required  bool
   }
   type CrudStoredProcConfig struct {
   	URIPath             string          // Path that will reach this end point
   	AuthKey             bool            // Require an auth_key
   	JWTKey              bool            // Require a JWT token authentntication header
   	StoredProcedureName string          // Name of stored procedure to call.
   	TableNameList       []string        // table name update/used in call (Info Only)
   	ParameterList       []ParamListItem // Pairs of values
   }

vals, inputData, id, err := GetStoredProcNames(www, req, SPData.ParameterList, SPData.StoredProcedureName, SPData.URIPath)

func GetTypeCode

func GetTypeCode(ty string) (rv string)

func GetUpdateNames

func GetUpdateNames(www http.ResponseWriter, req *http.Request, potentialCols []string, pkCol string) (updCols string, inputData []interface{}, id string, err error)

GetUpdateNmaes returns the set of update columns and the data values for running an udpate.

func GetUpdateNamesMulti

func GetUpdateNamesMulti(www http.ResponseWriter, req *http.Request, pos int, aMd map[string]string, potentialCols []string, pkCol string) (
	updCols string, inputData []interface{}, id string, err error,
)

updCols, inputData, id, err := GetUpdateNamesMulti(www, req, ii, aMd, CrudData.UpdateCols, CrudData.UpdatePkCol)

func GetUserId

func GetUserId(auth_token string) (user_id string, err error)

GetUserId queries the database to turn an `auth_token` into a `user_id'. Called from server layer and used to compare the passed user_id with the tokens user_id.

func GetValueFromSave

func GetValueFromSave(www http.ResponseWriter, req *http.Request, name string) (found bool, val string)

func GetVar

func GetVar(name string, www http.ResponseWriter, req *http.Request) (found bool, value string)

GetVar returns a variable by name from GET or POST data.

func GetVarDflt

func GetVarDflt(name string, www http.ResponseWriter, req *http.Request, dflt string) (found bool, value string)

Get value and if not found use the default value.

func HalfLifeDecay

func HalfLifeDecay(startValue float64, timeSpanInSeconds float64, halfLifeInSeconds float64) float64

HalfLifeDecay xyzzy

func Handle

func Handle(pattern string, handler http.Handler)

Handle registers the handler for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func HandleCRUDConfig

func HandleCRUDConfig(www http.ResponseWriter, req *http.Request, CrudData CrudConfig, posInTable int, gCfg *BaseConfigType)

func HandleFunc

func HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))

HandleFunc registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func HandleQueryConfig

func HandleQueryConfig(www http.ResponseWriter, req *http.Request, QueryData CrudQueryConfig, posInTable int, gCfg *BaseConfigType)

func HandleStoredProcedureConfig

func HandleStoredProcedureConfig(www http.ResponseWriter, req *http.Request, SPData CrudStoredProcConfig, posInTable int, gCfg *BaseConfigType)

handleSPClosure := func(cc CrudStoredProcConfig, ii int) func(www http.ResponseWriter, req *http.Request) {

func HandleTables

func HandleTables(mux *ServeMux, gCfg *BaseConfigType)

HandleTables creates a set of closure based functions for each of thie items in TableConfig. Each handler is for a single end point. Look at the comments for TableConfig for how to use this.

func HasOrderByList

func HasOrderByList(www http.ResponseWriter, req *http.Request) bool

func HasPageLimit

func HasPageLimit(www http.ResponseWriter, req *http.Request) bool

} else if HasPageLimit(www, req) {

func HasPort

func HasPort(s string) bool

Given a string of the form "host", "host:port", or "[ipv6::address]:port", return true if the string includes a port.

func HashFile

func HashFile(file_name string) (file_hash string, err error)

func HaveRow

func HaveRow(stmt, id string) bool

func HexEscapeNonASCII

func HexEscapeNonASCII(s string) string

func HtmlEscapeUrl

func HtmlEscapeUrl(s string) string

func InArray

func InArray(lookFor string, inArr []string) bool

func InArrayInt

func InArrayInt(lookFor int, inArr []int) bool

func InArrayStr

func InArrayStr(lookFor string, inArr []string) bool

func InArrayStrN

func InArrayStrN(lookFor string, inArr []string) int

func InsertBuild

func InsertBuild(stmt string, vars ...interface{}) (out_stmt string, data []interface{})

func Is1DollarGlobal

func Is1DollarGlobal(NameList []string) bool

func Is2DollarGlobal

func Is2DollarGlobal(NameList []string) bool

func IsANumber

func IsANumber(s string, www http.ResponseWriter, req *http.Request) (nv int, err error)

if n, err = IsANumber ( page, www, req ) ; err != nil {

func IsAuthKeyValid

func IsAuthKeyValid(www http.ResponseWriter, req *http.Request, gCfg *BaseConfigType) bool

func LiveMonSetup(name string, db_flag map[string]bool, gCfg *BaseConfigType) {

func IsAuthorized

func IsAuthorized(www http.ResponseWriter, req *http.Request) (err error)

func IsBool

func IsBool(s string) (ok bool)

IsBool returns true if one of the true/fals names

func IsHexNumber

func IsHexNumber(s string) (ok bool)

IsHexNumber returns true if composed of Optional 0x|0X followd by 0..9 a..f A..F

func IsInArray

func IsInArray(aName string, names []string) bool

IsInArray returns true if aName is in the list of names.

func IsInDemoMode

func IsInDemoMode(gCfg *BaseConfigType) bool

func IsInDemoModeCompoent

func IsInDemoModeCompoent(gCfg *BaseConfigType, c string) bool

func IsIntString

func IsIntString(s string) bool

IsIntString returns true if the string is composed of 0..0 digigts optionally with a +- at beginning.

func IsJWTValid

func IsJWTValid(www http.ResponseWriter, req *http.Request, db_flag map[string]bool, gCfg *BaseConfigType) bool

func IsNumber

func IsNumber(s string) (ok bool)

IsNumber returns true if the string is composed of 0..0 digigts optionally with a +- at beginning.

func IsTLS

func IsTLS(req *http.Request) bool

func IsTLSUrl

func IsTLSUrl(hp string) bool

func JsonEscQuote

func JsonEscQuote(s string) string

func JsonResponse

func JsonResponse(www http.ResponseWriter, code int, message string)

func KeysFromMap

func KeysFromMap(a interface{}) (keys []string)

KeysFromMap returns an array of keys from a map.

This is used like this:

keys := KeysFromMap(nameMap)
sort.Strings(keys)
for _, key := range keys {
	val := nameMap[key]
	...
}

func LenOfMatch

func LenOfMatch(matchTo []MuxMatchItem) int

func LiveMonSetup

func LiveMonSetup(name string, db_flag map[string]bool, logFile *os.File, gCfg *BaseConfigType)

Inputs - db_flag, name,

func LogFile

func LogFile(f *os.File)

var logFilePtr *os.File

func init() {

logFilePtr = os.Stderr

}

// LogFile sets the output log file to an open file. This will turn on logging of SQL statments.

func LoggingSetup

func LoggingSetup(gg *BaseConfigType) (f *os.File)

func LiveMonSetup(name string, db_flag map[string]bool, gCfg *BaseConfigType) {

func MatchOthersRRToMatcher

func MatchOthersRRToMatcher(www http.ResponseWriter, req *http.Request, matchOthers *MuxRREntry) (ok bool)

func MatchOthersToMatcher

func MatchOthersToMatcher(www http.ResponseWriter, req *http.Request, matchOthers *MuxEntry) (ok bool)

type MuxEntry struct {

h          http.Handler   //
AuthReq    bool           // requires authentication before a call to this can be made
MethodList []string       //
Name       string         // name used for identifying this in tests (basically a comment name)
MatchTo    []MuxMatchItem // match to a set of items.
Pattern    string         //

}

func MatchURIToMatcher

func MatchURIToMatcher(www http.ResponseWriter, req *http.Request, mm []string, matchTo []MuxMatchItem) (ok bool)

func MaxFloat64

func MaxFloat64(a, b float64) float64

MaxFloat64 returns the maximum of 2 float64 values.

func MethodReplace

func MethodReplace(www http.ResponseWriter, req *http.Request, db_flag map[string]bool) (methodOut string)

MethodReplace returns a new method if __method__ is a get argument. This allows for testing of code just using get requests. That is very convenient from a browser.

func MinFloat64

func MinFloat64(a, b float64) float64

MinFloat64 returns the minimum of 2 float64 values.

func MultiData

func MultiData(www http.ResponseWriter, req *http.Request) (raw string, found bool)

func MultiData ( www http.ResponseWriter, req *http.Request, CrudData CrudConfig, posInTable int) bool {

func MultiInsertUpdate

func MultiInsertUpdate(www http.ResponseWriter, req *http.Request, CrudData CrudConfig, raw string, posInTable int)

func NameTransform

func NameTransform(URIPath string) (rv string)

func NonNull

func NonNull(listCols []string, row map[string]interface{}) (rv []interface{}, nonNullFlag bool)

func OneSecondDispatch

func OneSecondDispatch()

OneSecondDispatch waits for a "kick" or a timeout and calls QrGenerate forever.

func PGCheckStoredProcedureNameParams

func PGCheckStoredProcedureNameParams(fd PGProc) (err error)

func PGCheckTableColumns

func PGCheckTableColumns(tab PGTable) (err error)

func ParseBool

func ParseBool(s string) (b bool)

ParseBool convers a string to bool based on the table of trueValues.

func ParseDoc

func ParseDoc(doc []byte, tag string) (name, desc string)

xyzzy - read in gCfg.DocMdFile and parse - find document section. DocMdFile string `json:"doc_md" default:"./tmpl/api-doc.md"` <h2>/api/v1/status</h2> vv.Name, vv.Desc = ParseDoc(doc, vv.DocTag) for .md the DocTag would be "## /api/v1/status", for .html <h2>/api/v1/status</h2>

func ParseYN

func ParseYN(s string) (b bool)

func ParserOrderBy

func ParserOrderBy(val string, www http.ResponseWriter, req *http.Request, CrudData CrudConfig, posInTable int, gCfg *BaseConfigType) (p, e []string)

func Ping

func Ping() string

Ping database to verify that we are actually connected.

func ReadCRUDConfiFile

func ReadCRUDConfiFile(fn string) error

func Redirect

func Redirect(w http.ResponseWriter, r *http.Request, url string, code int)

Redirect replies to the request with a redirect to url, which may be a path relative to the request path.

The provided code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.

If the Content-Type header has not been set, Redirect sets it to "text/html; charset=utf-8" and writes a small HTML body. Setting the Content-Type header to any value, including nil, disables that behavior.

func RedisClient

func RedisClient(db_flag map[string]bool, gCfg *BaseConfigType) (client *redis.Client, conFlag bool)

func LiveMonSetup(name string, dbFlag map[string]bool, cfgBase *BaseConfigType ) {

func RemoveEmptyPort

func RemoveEmptyPort(host string) string

RemoveEmptyPort strips the empty port in ":port" to "" as mandated by RFC 3986 Section 6.2.3.

func RenderIndexHTMLWithToken

func RenderIndexHTMLWithToken(www http.ResponseWriter, req *http.Request)

func RmZero

func RmZero(s string) (r string)

RmZero trims a traling .0 from a string. This is used for displaying floats as integer values. Mostly this is to fix the fact that JSON (JavaScript) only has a floating point number type.

func Round

func Round(input float64) float64

Round rouns a float64 to the nearest integer value.

func RoundToPennies

func RoundToPennies(f float64) float64

RoundToPennies generates a rouned to pennies value for a float64.

func RunPostFunctions

func RunPostFunctions(www http.ResponseWriter, req *http.Request, SPData CrudBaseConfig, posInTable int, inData string) (outData string, err error)

func RunPreFunctions

func RunPreFunctions(www http.ResponseWriter, req *http.Request, SPData CrudBaseConfig, posInTable int) (err error)

PrePostConfig []string //

func RunTemplate

func RunTemplate(TemplateFn string, name_of string, g_data map[string]interface{}) string

RunTemplate runs a template and get the results back as a string. This is the primary template runner for sending email.

func RunTemplateInline

func RunTemplateInline(TemplateBody string, g_data map[string]interface{}) string

func RunTemplateInlineString

func RunTemplateInlineString(TemplateBody string, g_data map[string]string) string

func RunTemplateString

func RunTemplateString(TemplateFn string, name_of string, g_data map[string]string) string

func SQLDelete

func SQLDelete(stmt string, data ...interface{}) (err error)

SQLDelete can run delete statements.

func SQLDeleteDB

func SQLDeleteDB(DB *sql.DB, stmt string, data ...interface{}) (nd int, err error)

SQLDeleteDB can run delete statements.

func SQLExec

func SQLExec(stmt string, data ...interface{}) (resultSet sql.Result, err error)

SQLExec will run command that returns a resultSet (think insert).

func SQLExecDB

func SQLExecDB(DB *sql.DB, stmt string, data ...interface{}) (resultSet sql.Result, err error)

SQLExecDB will run command that returns a resultSet (think insert).

func SQLInsert

func SQLInsert(stmt string, data ...interface{}) (err error)

SQLInsert can run insert statements that do not return data.

func SQLInsertDB

func SQLInsertDB(DB *sql.DB, stmt string, data ...interface{}) (ni int, err error)

SQLInsertDB can run insert statements that do not return data.

func SQLQuery

func SQLQuery(stmt string, data ...interface{}) (resultSet *sql.Rows, err error)

SQLQuery runs stmt and returns rows.

func SQLQueryDB

func SQLQueryDB(DB *sql.DB, stmt string, data ...interface{}) (resultSet *sql.Rows, err error)

SQLQueryDB runs stmt and returns rows.

func SQLQueryRow

func SQLQueryRow(stmt string, data ...interface{}) (aRow *sql.Row)

SQLQueryRow queries a single row and returns that data.

func SQLQueryRowDB

func SQLQueryRowDB(DB *sql.DB, stmt string, data ...interface{}) (aRow *sql.Row)

SQLQueryRowDB queries a single row and returns that data.

func SQLSelect

func SQLSelect(stmt string, data ...interface{}) (resultSet *sql.Rows, err error)

SQLSelect is SQLQuery under a different name.

func SQLSelectDB

func SQLSelectDB(DB *sql.DB, stmt string, data ...interface{}) (resultSet *sql.Rows, err error)

SQLSelectDB is SQLQuery under a different name.

func SQLSelectRow

func SQLSelectRow(stmt string, data ...interface{}) (aRow *sql.Row)

SQLSelectRow is SQLQueryRow under a different name.

func SQLSelectRowDB

func SQLSelectRowDB(DB *sql.DB, stmt string, data ...interface{}) (aRow *sql.Row)

SQLSelectRowDB is SQLQueryRow under a different name.

func SQLUpdate

func SQLUpdate(stmt string, data ...interface{}) (nr int, err error)

SQLUpdate can run update statements that do not return data.

func SQLUpdateDB

func SQLUpdateDB(DB *sql.DB, stmt string, data ...interface{}) (nr int, err error)

SQLUpdateDB can run update statements that do not return data.

func SaveConfigToDB

func SaveConfigToDB(items []SaveConfigItemType) (err error)

SaveConfigToDB takes a list of config items from gCfg and saves them to a config table in the database.

func SecureRandomAlphaString

func SecureRandomAlphaString(length int) (rstr string, err error)

func SecureRandomBytes

func SecureRandomBytes(length int) (bts []byte, err error)

SecureRandomBytes returns the requested number of bytes using crypto/rand

func SendKick

func SendKick()

func SendTimeout

func SendTimeout()

func SetCliOpts

func SetCliOpts(cc *string, ss []string)

func SetDbFlag

func SetDbFlag(d map[string]bool)

func SetDbType

func SetDbType(s string)

func SetJsonHdr

func SetJsonHdr(www http.ResponseWriter, req *http.Request)

func SetJsonPHdr

func SetJsonPHdr(www http.ResponseWriter, req *http.Request)

func SetValue

func SetValue(www http.ResponseWriter, req *http.Request, name, value string)

func SetupBulkAPI

func SetupBulkAPI(mux *ServeMux, gCfg *BaseConfigType, upload_path string)

ymux.SetupBulkAPIl(mux) // func (mux *ServeMux) CreateHandleBulkOperations() (handle func(www http.ResponseWriter, req *http.Request)) { up == UploadPath is $sb/UploadFile/UploadFileCfg .UploadPath

func SetupCrud

func SetupCrud(f *os.File, d map[string]bool)

func SetupDescHtml

func SetupDescHtml(mux *ServeMux)

func SetupProcCheck

func SetupProcCheck()

func Sha1String

func Sha1String(s string) []byte

func SplitURI

func SplitURI(uri string) (result []string)

4. Split URL path into components then match by components.

/abc/def/ghi -> []{"abc","def","ghi"}

cleans URI

func SplitWithEsc

func SplitWithEsc(ss string, sep byte, stop byte) (rv []string)

SplitWithEsc slices s into all substrings separated by sep and returns a slice of the substrings between those separators. It honors \ chars.

func Start1SecTimer

func Start1SecTimer()

func StripHostPort

func StripHostPort(h string) string

StripHostPort returns h without any trailing ":<port>".

func TLSSetup

func TLSSetup(TLS_crt, TLS_key *string, gCfg *BaseConfigType) bool

func TemplateProcessInputData

func TemplateProcessInputData(inputData *CrudBulkFileFormat, colNames []string, www http.ResponseWriter, req *http.Request, GlobalData []CrudBulkGloalConfig, gdata map[string]interface{}) (err error)

func TestConnectToDB

func TestConnectToDB()

func TestSetLogFilePtr

func TestSetLogFilePtr()

func UpdateBuild

func UpdateBuild(stmt string, npk int, vars ...interface{}) (out_stmt string, data []interface{})

func ValidEmailAddress

func ValidEmailAddress(em string, data interface{}, data2 []string) bool

func ValidInList

func ValidInList(em string, data interface{}, data2 []string) bool

func ValidInListQry

func ValidInListQry(em string, data interface{}, dataX []string) bool

func ValidList

func ValidList(em string, data interface{}, data2 []string) bool

"list": ValidList,

func ValidListInsensitive

func ValidListInsensitive(em string, data interface{}, data2 []string) bool

"list_case_insensitive": ValidListInsensitive,

func ValidUSZip

func ValidUSZip(em string, data interface{}, data2 []string) bool

func ValidateAuthToken

func ValidateAuthToken(www http.ResponseWriter, req *http.Request, auth_token string, db_flag map[string]bool, gCfg *BaseConfigType) (tokenValid bool)

func ValidateCSRFTokenJwtToken

func ValidateCSRFTokenJwtToken(CsrfToken string, www http.ResponseWriter, req *http.Request) bool

func ValidateStoredProcs

func ValidateStoredProcs(sp []CrudStoredProcConfig)

func ValidateTemplateHas

func ValidateTemplateHas(TemplateFn string, nameSet []string) (err error)

- check that the template has all necessary named-temlates in it. (Function)

func ValidateTemplates

func ValidateTemplates(fns ...string) (rv bool)

func VerifyToken

func VerifyToken(tokData []byte, keyFile string, db_flag map[string]bool, gCfg *BaseConfigType) (iat string, err error)

Verify a token and output the claims. This is a great example of how to verify and view a token.

func YearsToSeconds

func YearsToSeconds(yr float64) (sec float64)

YearsToSeconds converts a number of years to seconds

Types

type AValue

type AValue map[string]string

type BaseConfigType

type BaseConfigType struct {

	// do not change - do not edit next line.
	Status string `json:"status" default:"success"`

	// Add in Redis stuff
	RedisConnectHost string `json:"redis_host" default:"$ENV$REDIS_HOST"`
	RedisConnectAuth string `json:"redis_auth" default:"$ENV$REDIS_AUTH"`
	RedisConnectPort string `json:"redis_port" default:"6379"`

	TickerSeconds int `json:"ticker_seconds" default:"30"` // Time Ticker Seconds

	// connect to Postgres Stuff
	DBHost          string `json:"db_host" default:"$ENV$PG_HOST"`
	DBPort          int    `json:"db_port" default:"5432"`
	DBUser          string `json:"db_user"`
	DBPassword      string `json:"db_password" default:"$ENV$PG_AUTH"`
	DBName          string `json:"db_name"`
	DBSSLMode       string `json:"db_sslmode" default:"disable"`
	LogFileName     string `json:"log_file_name"`
	DBConnectString string `json:"connectToPostgreSQL" default:"$ENV$connectToPostgreSQL"` // Full connect string instead of "above

	// Auth Related Stuff ------------------------------------------------------------------------------------------------------------------------------------------------------------
	AuthRealm                string `json:"auth_realm" default:"*" pgsave:"AuthRealm"`                                           //
	Auth2faEnabled           string `json:"auth_2fa_enabled" default:"no" pgsave:"Auth2faEnabled"`                               //
	UseEmailConfirm          string `json:"use_email_confirm" default:"no" pgsave:"UseEmailConfirm"`                             //
	AuthLoginOnRegister      string `json:"auth_login_on_register" default:"no" pgsave:"AuthLoginOnRegister"`                    //
	UseRegistrationToken     string `json:"use_registration_token" default:"yes" pgsave:"UseRegistrationToken"`                  //
	UseTOTPSkew              int    `json:"use_totp_skew" default:"1" pgsave:"UseTOTPSkew"`                                      //
	AuthMethod               string `json:"auth_method" default:"key" validate:"v.In(['key','jwt'])" pgsave:"AuthMethod"`        // key or jwt for the moment
	AuthKey                  string `json:"auth_key" default:""`                                                                 //
	AuthJWTPublic            string `json:"auth_jwt_public_file" default:""`                                                     // Public Key File
	AuthJWTPrivate           string `json:"auth_jwt_private_file" default:""`                                                    // Private Key File
	AuthJWTKeyType           string `json:"auth_jwt_key_type" default:"ES" validate:"v.In(['ES256','RS256', 'ES512', 'RS512'])"` // Key type ES = ESDSA or RS = RSA
	AuthJWTSource            string `json:"auth_jwt_source" default:"Authorization"`                                             // Valid forms for getting authorization
	AuthTokenValidate        string `json:"auto_token_validate" default:"no"`                                                    //
	AuthTokenURI             string `json:"auth_token_uRI" default:"http://127.0.0.1:9019/api/admin/validate-token"`             //
	AuthTokenLifetime        int    `json:"auth_token_lifetime" default:"3540" pgsave:"AuthTokenLifetime"`                       // Lifetime is in seconds - this is under 1 hour (3600 is hour)
	AuthEmailConfirm         string `json:"auth_email_confirm" default:"yes" pgsave:"AuthEmailConfirm"`                          //
	Auth2faSetupApp          string `json:"auth_2fa_setup_app" default:"http://2fa.simple-auth.com/setup.html"`                  // xyzzy - should be 192.154.97.75 2fa.simple-auth.com
	Auth2faAppNoEmail        string `json:"auth_2fa_app_no_email" default:"http://2fa.simple-auth.com/app.html"`                 // xyzzy - should be 192.154.97.75 2fa.simple-auth.com
	AuthSelfURL              string `json:"auth_self_url" defaulit:"http://2fa.simple-auth.com"`                                 // where to call to get info on this user.
	AuthQrURL                string `json:"auth_qr_url" defaulit:"http://2fa.simple-auth.com"`                                   // where to call to QR images painted
	AuthApplicationName      string `json:"auth_application_name" defaulit:"Simple Auth"`                                        // Name of applicaiton for use in templates
	AuthRedirect2faSetupPage string `json:"auth_redirect_2fa_setup_page" default:"/2fa-setup-page.html"`                         // page to redirect to when 2fa setup is used.

	// debug flags:	 Comma seperated values in the config file.
	// 	 test-http-end-points			Turn on extra end-points for testing code.   Tests are in Makefile.
	//	 dump-db-flag				  	Print out the db flags that are set.
	//   GetVal							Echo variables that are fetched.
	//   RedisClient					Report on connedtion to Redis
	//   Cli.Where						Dump out where the writes to the output http buffer occure.
	//   Cli.Write
	//   cli
	//   test-print-command-success
	// From MonAliveLib
	// 		MonAliveLib.report-config	Reprot if defauilt config is used.
	DebugFlag string `json:"db_flag"`

	// xyzzy - Demo Mode - xyzzy
	// URL := "http://www.2c-why.com/Ran/RandomValue"
	RandomOracleURL string `json:"random_oracle_url" default:"http://www.2c-why.com/Ran/RandomValue"`

	// 1. template(s) for ./desc.html -> ./tmpl/desc.html.tmpl
	DescHtmlTemplate string `json:"desc_html_tmpl" default:"./tmpl/desc.html.tmpl"`
	DocMdFile        string `json:"doc_md" default:"./tmpl/api-doc.md"`

	// Defauilt file for TLS setup (Shoud include path), both must be specified.
	// These can be over ridden on the command line.
	TLS_crt string `json:"tls_crt" default:""`
	TLS_key string `json:"tls_key" default:""`

	// S3 login/config options.
	// Also uses
	//		AWS_ACCESS_KEY_ID=AKIAJZ...........VWA		((example))
	//		AWS_SECRET_KEY=........
	S3_bucket string `json:"s3_bucket" default:"s3://documents"`
	S3_region string `json:"s3_region" default:"$ENV$AWS_REGION"`

	// Path for static files
	StaticPath string `json:"static_path" default:"www"`

	// Remote validation of "auth_token" from JWT Token.
	RemoteAuthServer       string `json:"remote_auth_server" default:"http://www.simple-auth.com:9019"`
	RemoteAuthGetTokenInfo string `json:"remote_auth_server" default:"http://www.simple-auth.com:9019/api/v1/get-token-info"`
	RemoteAuthTTL          int    `json:"remote_auth_ttl" default:"120"`                  // In seconds
	RemoteAuthKey          string `json:"remote_auth_ttl" default:"$ENV$SIMPLE_AUTH_KEY"` // In seconds

	// JS/HTML can be templated to produce a configuration
	// var URLRegister = "http://127.0.0.1:9019/api/session/register_immediate";
	// var URLRegister = "http://www.simple-auth.com:9019/api/session/register_immediate";
	TemplateDir         string `default:"./tmpl"`
	TemplatedFiles      string `default:"/js/x-config.js"`
	URL__Auth__Register string `json:"URL__Auth__Register" default:"$ENV$URL__Auth__Register"`

	JWTUsed            bool
	URL__JWT__Validate string `json:"URL__JWT__Validate" default:"$ENV$URL__JWT__Validate"`
	JWT_KeyFile        string `json:"jwt_key_file_dir" default:"./test-key"`
	JWT_Ecdsa          string `json:"jwt_ecdsa" default:"no"` // using RSA until figure out how to sign ecdsa for test
	JWT_RSA            string `json:"jwt_rsa" default:"yes"`

	// Authentication configuration items
	PasswordResetPage string `json:"password_reset_uri" default:"/password_reset.html?token={{.token}}"`

	// Authentication configuration items
	AppliationMainPage       string `json:"main_uri" default:"/index.html"`
	ImmediateLoginOnRegister string `json:"immediate_login_on_register" default:"yes"`
	EmailTmplDir             string `json:"email_template_dir" default:"./tmpl"`
	EmailFromName            string `json:"email_from_name" default:"Authentication"`
	EmailFromAddress         string `json:"email_from_address" default:"pschlump@gmail.com"`
	RFC6238_2fa_on           string `json:"rfc_6238_2fa_on" default:"no"`
	RFC6238_2fa_NDigits      int    `json:"rfc_6238_2fa_n_digits" default:"6"`
	RFC6238_RedisKey         string `json:"rfc_6238_redi_key" default:"qr2fa:"`
	RFC6238_QR_TTL           int    `json:"rfc_6238_ttl" default:"172800"` // 2 days = 24 * 60 * 60 * 2
	Use14DayCookie           string `json:"use_14_day_cookie" default:"yes"`

	UseRolePriv string `json:"use_role_priv" default:"yes"`

	CachForPwned string `json:"cache_for_pwned" default:"./pwned_cache"`

	BaseServerUrl string `json:"base_server_url" default:"http://www.q8s.com"` // urlBase := "http://www.q8s.com"

	// xyzzy - Demo Mode - xyzzy
	DemoFlag string `json:"demo_flag" default:"no"` // if "yes" then in demo mode. CSV value, yes,RandomOracle,2FA,Login,QRCode,Geth

	BusinessAuthToken string `json:"business_auth_token" default:"no"` // Not implemented yet - jsut read in.  Requires a "auth-token" for user to register.

	EmailRegistrationToken string `json:"email_registration_token" default:"no"`

	// xyzzy TODO - encrypte IsSecret values into log file using following key
	LogFileEncryptionKey string `json:"log_file_encryption_key" default:"$ENV$LOG_ENCRYPTION_KEY"`

	DB_Enc_Key string `json:"DB_Enc_Key" default:"$ENV$DB_ENC_KEY"`
	DB_IV_Data string `json:"DB_IV_Data" default:"$ENV$DB_ENC_IV_DATA"`

	CSRF_Token string `json:"CSRF_Token" default:"X-CSRF-Token"`
	// contains filtered or unexported fields
}

type BodyConfig

type BodyConfig struct {
	ColumnName string
	ColumnPos  int
}

type ContextType

type ContextType struct {
	Value map[*http.Request]AValue
}
var SaveValue ContextType

type CrudBaseConfig

type CrudBaseConfig struct {
	URIPath          string               // Path that will reach this end point
	AuthKey          bool                 // Require an auth_key
	JWTKey           bool                 // Require a JWT token authentication header (logged in)
	TableNameList    []string             // table name update/used in call (Info Only)
	ParameterList    []ParamListItem      // Pairs of values
	ProcReturnValue  []ProcReturnValueSet // Set of Pairs of values
	RawDataType      string               //
	PreProc          []string             // Functions to call before the store procedure
	PreConfig        []string             //
	PostProc         []string             // Functions to call after the return from the S.P.
	PostConfig       []string             //
	NoDoc            bool                 // Turn of documentation on this API
	DocTag           string               // Documentation tag for lookup and display of doc.
	AuthPrivs        []string             // Prives that are required to access this end point (requires login/auth_token/jwt)
	InputList        []*MuxInput          // Validation of inputs for htis call
	MultiRowReturn   bool                 // If true then query can return 0..n rows v.s false 1 row.
	MuxName          string               // Name used for generation of code in desc.html
	NoValidate       bool                 // Skip all validation - useful for items like files that do not have an active component.
	FileWhereDefined string               // debugging info on where the definition comes from
}

type CrudBulkAllowed

type CrudBulkAllowed struct {
	APIEndpoint string   //
	Method      []string //
	NoDoc       bool     // Turn of documentation on this API
	DocTag      string   // Documentation tag for lookup and display of doc.
	AuthReq     bool     //
	AuthPrivs   []string // Prives that are requried to access this end point (requires login/auth_token/jwt)
	GlobalData  []CrudBulkGloalConfig
}

------------------------------------------------------------------------------------------------------------------------------------------ CrudBulkConfig is the setup for allowing bulk operations. Bulk operations are in 2 passes. 1. Upload a file of data in bulk format. 2. Process it multiple times.

type CrudBulkConfig

type CrudBulkConfig struct {
	BulkAPIAllowed []CrudBulkAllowed
	// contains filtered or unexported fields
}

type CrudBulkFileFormat

type CrudBulkFileFormat struct {
	APIEndPoint string          `json:"bulk_api"`    // tempalteded api endpoint
	APIMethod   string          `json:"bulk_method"` // Method to use
	Params      []CrudBulkParam `json:"params"`      //
}

type CrudBulkGloalConfig

type CrudBulkGloalConfig struct {
	NameList   []string // $$owner, $$custodian, $$user_id etc.
	Stmt       string   // select "id" as "owner", "id" as "custodian", "id" as "user_id", "email", "username" from "t_ymux_user" where "id" in ( select "parent_user_id" from "t_ymux_user" where "id" = $1 )
	Bind       []string // user_id
	InsertStmt string   // `select s_create_parent ( $1, $2 ) as "x"`, // create on demand?
	InsertBind []string // []string{"$parents_sire", "user_id"},
	Required   bool     // if true then 0 results on 'Stmt' is error
}

type CrudBulkParam

type CrudBulkParam map[string]string

This is the format for the uploaded (or posted) file that provides input for bulk processing.

type CrudBulkReturnFormat

type CrudBulkReturnFormat struct {
	Status       string              `json:"status"` // one of 'success', 'partial', 'error'
	PerRowStatus []CurdBulkReturnMsg `json:"per_row_status"`
}

type CrudColTypeData

type CrudColTypeData struct {
	Name string `json:"ColTypeName"`
	Type string `json:"ColTypeType"`
}

------------------------------------------------------------------------------------------------------------------------------------------

type CrudConfig

type CrudConfig struct {
	CrudBaseConfig
	MethodsAllowed      []string          `json:"MethodsAllowed"`      // Set of methods that are allowed
	TableName           string            `json:"TableName"`           // table name
	InsertCols          []string          `json:"InsertCols"`          // Valid columns for insert
	ColsTypes           []CrudColTypeData `json:"ColsTypes"`           // Type of columns for thins like 'box'
	InsertPkCol         string            `json:"InsertPkCol"`         // PK during insert
	UpdateCols          []string          `json:"UpdateCols"`          // Valid columns for update
	UpdatePkCol         string            `json:"UpdatePkCol"`         // PK during update
	WhereCols           []string          `json:"WhereCols"`           // Set of columns that can be used in the "where" clause.
	OrderByCols         []string          `json:"OrderByCols"`         // Set of columns that can be used in the "order by" clause.
	SelectRequiresWhere bool              `json:"SelectRequiresWhere"` // if true, then where must be specified -- can not return entire table.
	ProjectedCols       []string          `json:"ProjectedCols"`       // Set of columns that are projected in a select (GET).
	InsertAuthPrivs     []string          // Prives that are requried to access this end point (requires login/auth_token/jwt)
	UpdateAuthPrivs     []string          // Prives that are requried to access this end point (requires login/auth_token/jwt)
	DeleteAuthPrivs     []string          // Prives that are requried to access this end point (requires login/auth_token/jwt)
	SelectAuthPrivs     []string          // Prives that are requried to access this end point (requires login/auth_token/jwt)
	PKUKList            [][]string        // xyzzy - PK/UK List - limit updates to require PK/UK in data. And supply ordering info. (xyzzy - Checked Automatically on Startup)
}

type CrudQueryConfig

type CrudQueryConfig struct {
	CrudBaseConfig
	QueryString string // "select ... from tables where {{.where}} {{.order_by}}
	SubQuery    []CrudSubQueryConfig
	// SelectCols  []string `json:"SelectCols"` // Valid columns for projected data -- See ParameterList
	// SelectWhereCols  []string `json:"SelectCols"` // Valid columns for where -- See ParameterList
	// UpdateCols  []string `json:"SelectCols"` // Valid columns for update -- See ParameterList
	// UpdateKeys  [][]string `json:"SelectCols"` // Valid columns for update -- See ParameterList
	// InsertCols  []string `json:"SelectCols"` // Valid columns for update -- See ParameterList
	// DeleteKeys  [][]string `json:"SelectCols"` // Valid columns for update -- See ParameterList
	// DeleteCascade  bool `json:"SelectCols"` // Valid columns for update -- See ParameterList
	// DeleteStmt  string `json:"SelectCols"` // Valid columns for update -- See ParameterList
	PrimayTableName string // MuxName
	HeaderInfo      []HeaderConfig
	BodyInfo        []BodyConfig
	IsUpdate        bool
	IsDelete        bool
	IsInsert        bool
}

type CrudStoredProcConfig

type CrudStoredProcConfig struct {
	CrudBaseConfig
	StoredProcedureName string // Name of stored procedure to call.
}

func GetStoredProcDefinition

func GetStoredProcDefinition(name string) (rv CrudStoredProcConfig, err error)

type CrudSubQueryConfig

type CrudSubQueryConfig struct {
	BindValues []string // [ "id" ]
	To         string   // event_list - place to put the data result.
	QueryTmpl  string   // select * from "event" where "item_id" = $1 order by "seq"

	PrimayTableName string // MuxName
	HeaderInfo      []HeaderConfig
	BodyInfo        []BodyConfig
	SubQuery        []CrudSubQueryConfig // Recursive
}

type CurdBulkReturnMsg

type CurdBulkReturnMsg struct {
	Nth      int    `json:"Nth"`
	Status   int    `json:"Status"`
	Msg      string `json:"Msg,omitempty"`
	RespData string `json:"RespData,omitempty"`
}

Assume that a row is successful unless it has a nth and a message in this set.

type DbColumnsType

type DbColumnsType struct {
	ColumnName string
	DBType     string
	TypeCode   string
}

type DbTableType

type DbTableType struct {
	TableName string
	DbColumns []DbColumnsType
}

func GetFunctionInformationSchema

func GetFunctionInformationSchema(FunctionName string, DbSchema string) (rv DbTableType, err error)

SELECT routines.routine_name, parameters.data_type, parameters.ordinal_position FROM information_schema.routines

JOIN information_schema.parameters ON routines.specific_name=parameters.specific_name

WHERE routines.specific_schema='public' ORDER BY routines.routine_name, parameters.ordinal_position;

type GetStatusType

type GetStatusType struct {
	Status         string
	HttpStatusCode int    `json:"status_code"`
	Msg            string `json:"msg"`
}

------------------------------------------------------------------------------------------------------------------------------------------

type HeaderConfig

type HeaderConfig struct {
	ColumnTitle string
	ColumnName  string
	ColumnPos   int
}

type InjectList

type InjectList struct {
	Name      string // $nth$
	ParamName string // nth
	Value     string // {{.ii}}
}

type InvalidInputType

type InvalidInputType struct {
	Mux *ServeMux
	Pos int
	Err error
}

func (*InvalidInputType) ServeHTTP

func (ih *InvalidInputType) ServeHTTP(www http.ResponseWriter, req *http.Request)

type MatchFunc

type MatchFunc func(www http.ResponseWriter, req *http.Request, path string) bool

type MultiRv

type MultiRv struct {
	Status string `json:"status"`
	Msg    string
	RowNum int
	Id     string
}

type MuxAdditionalCriteria

type MuxAdditionalCriteria struct {
	// contains filtered or unexported fields
}

func (*MuxAdditionalCriteria) AuthPotentiallyRequired

func (mm *MuxAdditionalCriteria) AuthPotentiallyRequired() *MuxAdditionalCriteria

func (*MuxAdditionalCriteria) AuthPrivs

func (mm *MuxAdditionalCriteria) AuthPrivs(p ...string) *MuxAdditionalCriteria

func (*MuxAdditionalCriteria) AuthRequired

func (mm *MuxAdditionalCriteria) AuthRequired() *MuxAdditionalCriteria

AuthRequried turns on authentication requirement for this path.

func (*MuxAdditionalCriteria) Desc

func (*MuxAdditionalCriteria) DocTag

func (*MuxAdditionalCriteria) Func

func (*MuxAdditionalCriteria) Host

func (*MuxAdditionalCriteria) Inputs

Input []MuxInput `json:"Input"` //

func (*MuxAdditionalCriteria) Method

func (*MuxAdditionalCriteria) MultiRowReturn

func (mm *MuxAdditionalCriteria) MultiRowReturn(b ...bool) *MuxAdditionalCriteria

func (*MuxAdditionalCriteria) MuxName

func (*MuxAdditionalCriteria) Name

func (*MuxAdditionalCriteria) NoDoc

NoDoc turns off automatic documentation display. For example the / for returning files is not an API end point and documentation is not appropriate for that path.

func (*MuxAdditionalCriteria) NoValidate

func (mm *MuxAdditionalCriteria) NoValidate(b ...bool) *MuxAdditionalCriteria

func (*MuxAdditionalCriteria) Port

func (*MuxAdditionalCriteria) Scheme

type MuxEntry

type MuxEntry struct {
	Pos                int            `json:"Pos"`                // what array subscript is this
	AuthReq            bool           `json:"AuthRequired"`       // requires authentication before a call to this can be made
	AuthPotentiallyReq bool           `json:"AuthPotentiallyReq"` // may or may not require auth - based on other criteria -
	AuthPrivs          []string       `json:"AuthPrivs"`          // Prives that are requried to access this end point (requires login/auth_token/jwt)
	MethodList         []string       `json:"MethodList"`         //
	HostList           []string       `json:"HostList"`           //
	SchemeList         []string       `json:"SchemeList"`         //	what about ws: wss::
	PortList           []string       `json:"PortList"`           //
	Name               string         `json:"Name"`               // name used for identifying this in tests (basically a comment name)
	Desc               string         `json:"Desc"`               //
	DocTag             string         `json:"DocTag"`             // "##String" in document describing this. (Use instead of Name/Desc)
	NoDoc              bool           `json:"NoDoc"`              // Do not document this end point
	MatchTo            []MuxMatchItem `json:"MatchTo"`            // match to a set of items.
	Pattern            string         `json:"Pattern"`            //
	UrlPattern         string         `json:"UrlPattern"`         // Pattern encoded for front end QT templates %{name%}
	CurlSample         string         `json:"CurlSample"`         //
	Fx                 MatchFunc      `json:"-"`                  //
	Input              []*MuxInput    `json:"Input"`              //
	NoValidate         bool           `json:"NoValidate"`         //
	MuxName            string         `json:"MuxName"`            //	User-Specified Name For Mux API Entry
	MultiRowReturn     bool           `json:"MultiRowReturn"`     //
	// contains filtered or unexported fields
}

type MuxInput

type MuxInput struct {
	Name           string      `json:"Name"`                 //	Field Name
	AltName        []string    `json:"AltName,omitempty"`    // Alternate names list - if ReqVar is not there then pull each of these and set as ReqVar
	Label          string      `json:"Lable,omitempty"`      //	Used for auto-generation of forms - this is the printed label for input.
	Default        string      `json:"Dflt,omitempty"`       //	Default if not specified in input
	Type           string      `json:"Ty"`                   //	Type { 's', 'i', 'f', 'u' }
	MinLen         int         `json:"MinLen"`               //	If > 0 then the minimum length - not checked if 0
	MaxLen         int         `json:"MaxLen"`               //	If > 0 then the maximum length - not checked if 0
	Required       bool        `json:"Required"`             //	If true then this is a required value.
	Validate       string      `json:"Val,omitempty"`        //	A named validation like "email" or "us_zip" can be extended with calls to AddValidationFunction
	ValidationData interface{} `json:"ValData"`              //	Set of Data
	ListValues     []string    `json:"ListValues,omitempty"` //	A named validation like "email" or "us_zip" can be extended with calls to AddValidationFunction
	IsSecret       bool        `json:"IsSecret"`             // xyzzy TODO - do not log secret values (value replace with encrypted entry)
	LineFile       string      `json:"-"`                    //	What line was it called from
	MinVal         int64       `json:"MinVal"`               //	Integer Value Range Inclusive
	MaxVal         int64       `json:"MaxValLen"`            //	Integer Value Range Inclusive
	UseMinVal      bool        `json:"UseMinVal"`            //	Integer Value Range Inclusive
	UseMaxVal      bool        `json:"UseMaxVal"`            //	Integer Value Range Inclusive
}

type MuxMatchItem

type MuxMatchItem struct {
	MatchType MuxMatchType   `json:"MatchTypeStr"` //
	To        string         `json:"To"`           //
	VarName   string         `json:"VarName"`      //
	Re        *regexp.Regexp `json:"-"`            //
	LenOp     string         `json:"LenOp"`        // < <= == > >= !=
	LenVal    int            `json:"Lenval"`       //
	Msg       string         `json:"ErrorMsg"`     //
	Fx        MatchFunc      `json:"-"`            //
}

func GenerateMatchTo

func GenerateMatchTo(uriMatchTo string) (mt []MuxMatchItem)

MatchTo []MuxMatchItem // ... matcher for set of UriMatchTo -- generated from UriMatchToComponents

func ParseMatcher

func ParseMatcher(mm string) (rv MuxMatchItem, err error)

type MuxMatchType

type MuxMatchType int
const (
	MuxMatchTypeError     MuxMatchType = 0
	MuxMatchTypeString    MuxMatchType = 1 // match value to .to
	MuxMatchTypeNumber    MuxMatchType = 2 // match to [0-9]+
	MuxMatchTypeText      MuxMatchType = 3 // ??? what is diff betwen this and MuxMatchTypeString   ?
	MuxMatchTypeRE        MuxMatchType = 4
	MuxMatchTypeFunc      MuxMatchType = 5
	MuxMatchTypeAnyString MuxMatchType = 6  // match to any string of any length
	MuxMatchTypeUUID      MuxMatchType = 7  // UUID match
	MuxMatchTypeBoolean   MuxMatchType = 8  // true/false
	MuxMatchTypeHexNumber MuxMatchType = 9  // 0xAAA or AAA
	MuxMatchTypeLen       MuxMatchType = 10 // Some length Op
	MuxMatchTypeEndRest   MuxMatchType = 11 // whatever is leftover
)

func DecodeMuxMatchTypeString

func DecodeMuxMatchTypeString(ss string) (rv MuxMatchType, err error)

xx, err := DecodeMuxMatchTypeString(objMap)

func (MuxMatchType) MarshalJSON

func (ww MuxMatchType) MarshalJSON() ([]byte, error)

func (MuxMatchType) String

func (mm MuxMatchType) String() string

func (*MuxMatchType) UnmarshalJSON

func (ww *MuxMatchType) UnmarshalJSON(b []byte) error

type MuxRRAdditionalCriteria

type MuxRRAdditionalCriteria struct {
	// contains filtered or unexported fields
}

func (*MuxRRAdditionalCriteria) AddQuery

func (mm *MuxRRAdditionalCriteria) AddQuery(varName, valName string) *MuxRRAdditionalCriteria

xyzzy40 - make variable list of pairs

func (*MuxRRAdditionalCriteria) AddQueryConst

func (mm *MuxRRAdditionalCriteria) AddQueryConst(varName, value string) *MuxRRAdditionalCriteria

func (*MuxRRAdditionalCriteria) AuthPotentiallyRequired

func (mm *MuxRRAdditionalCriteria) AuthPotentiallyRequired() *MuxRRAdditionalCriteria

func (*MuxRRAdditionalCriteria) AuthPrivs

func (*MuxRRAdditionalCriteria) AuthRequired

AuthRequried turns on authentication requirement for this path.

func (*MuxRRAdditionalCriteria) Desc

func (*MuxRRAdditionalCriteria) DocTag

func (*MuxRRAdditionalCriteria) GenProtoBuf

func (mm *MuxRRAdditionalCriteria) GenProtoBuf(typeOf string) *MuxRRAdditionalCriteria

func (*MuxRRAdditionalCriteria) GenProtoBufEnum

func (mm *MuxRRAdditionalCriteria) GenProtoBufEnum(val_names []string) *MuxRRAdditionalCriteria

func (*MuxRRAdditionalCriteria) MatchFinal

func (*MuxRRAdditionalCriteria) Method

func (*MuxRRAdditionalCriteria) MethodFromTo

func (mm *MuxRRAdditionalCriteria) MethodFromTo(mf, mt string) *MuxRRAdditionalCriteria

xyzzy40 - make variable list of pairs

func (*MuxRRAdditionalCriteria) MultiRowReturn

func (mm *MuxRRAdditionalCriteria) MultiRowReturn(b ...bool) *MuxRRAdditionalCriteria

func (*MuxRRAdditionalCriteria) MuxName

func (*MuxRRAdditionalCriteria) Name

xyzzy40 - Add ability to do Documents and NoDoc xyzzy40 - Add grouping of API - into named/described groups.

func (*MuxRRAdditionalCriteria) NoDoc

NoDoc turns off automatic documentation display. For example the / for returning files is not an API end point and documentation is not appropriate for that path.

func (*MuxRRAdditionalCriteria) NoValidate

type MuxRREntry

type MuxRREntry struct {
	Pos                int              `json:"Pos"`                // what array subscript is this
	AuthReq            bool             `json:"AuthRequired"`       // requires authentication before a call to this can be made
	AuthPotentiallyReq bool             `json:"AuthPotentiallyReq"` // may or may not require auth - based on other criteria -
	AuthPrivs          []string         `json:"AuthPrivs"`          // Prives that are requried to access this end point (requires login/auth_token/jwt)
	MethodList         []string         `json:"MethodList"`         //
	MethodListTo       []string         `json:"MethodList"`         //
	Name               string           `json:"Name"`               // name used for identifying this in tests (basically a comment name)
	Desc               string           `json:"Desc"`               //
	DocTag             string           `json:"DocTag"`             // "##String" in document describing this. (Use instead of Name/Desc)
	NoDoc              bool             `json:"NoDoc"`              // Do not document this end point
	MatchTo            []MuxMatchItem   `json:"MatchTo"`            // match to a set of items.
	Pattern            string           `json:"Pattern"`            //
	UrlPattern         string           `json:"UrlPattern"`         // Pattern encoded for front end QT templates %{name%}
	CurlSample         string           `json:"CurlSample"`         //
	Fx                 MatchFunc        `json:"-"`                  // TODO - not implemented yet.
	ReplaceTmpl        string           `json:"ReplaceTmpl"`        // Replacement template for URL if match occurs (QT Template Format?)
	Final              bool             `json:"Final"`              //
	QueryName          []QueryNameMap   `json:"QueryNameMap"`       //
	QueryConst         []QueryNameValue `json:"QueryNameValue"`     //
	NoValidate         bool             `json:"NoValidate"`         //
	MuxName            string           `json:"MuxName"`            //	User name
	MultiRowReturn     bool             `json:"MultiRowReturn"`     //
}

type PGColumn

type PGColumn struct {
	ColumnName string
}

type PGProc

type PGProc struct {
	FunctionName string
	Columns      []PGColumn
}

type PGTable

type PGTable struct {
	TableName string
	Columns   []PGColumn
}

type ParamListItem

type ParamListItem struct {
	ReqVar         string // variable for GetVar()
	ParamName      string // Name of variable (Checked v.s. stored procedure name variable names)
	AutoGen        string // TODO Is automatically generated value (think UUID, Random or Sequence)
	Required       bool   // Verify that value is supplied (check if this is implemented)
	MinLen, MaxLen int    // Validation- 0 implied not used.
	DefaultValue   string // Will convert from string to type. If value is ""
	DataType       string // Validation- used for validation also.
	ValidationData string // Validation- Lookkup a sub-type for validation of that type (email, uuid etc)
}

type PrePostFlag

type PrePostFlag int
const (
	PreFlag  PrePostFlag = 1
	PostFlag PrePostFlag = 2
)

type PrePostFx

type PrePostFx func(www http.ResponseWriter, req *http.Request, pp PrePostFlag, cfgData, inData string) (outData string, status StatusType, err error)

type ProcReturnValueItem

type ProcReturnValueItem struct {
	ParamName    string // Name of variable (Checked v.s. stored procedure name variable names)
	DataType     string // Validation- used for validation also.
	DefaultValue string // If ParamName is not in data, than take default value convert to type and use that.
}

type ProcReturnValueSet

type ProcReturnValueSet struct {
	Status      string
	ReturnValue []ProcReturnValueItem // Pairs of values
}

type QueryNameMap

type QueryNameMap struct {
	From string
	To   string
}

type QueryNameValue

type QueryNameValue struct {
	Name  string
	Value string
}

type RanData

type RanData struct {
	Status string `json:"status"`
	Value  string `json:"value"`
	TTL    int    `json:"ttl"`
	Epoc   int    `json:"ep"`
}

type RequestError

type RequestError struct {
	LineFile        string   // where generated	// added by ErrorReturn
	Status          int      // Status code
	DetailedMessage string   `json:",omitempty"` // English Message
	ClientMessage   string   `json:",omitempty"` // JSON client message
	RequestURI      string   `json:",omitempty"` //
	RequestMethod   string   `json:",omitempty"` //
	Params          []string `json:",omitempty"` //
	UUID            string   `json:",omitempty"` // UUID for this error // added by ErrorReturn
	Stmt            string   `json:",omitempty"` //
	Context         string   `json:",omitempty"` //
	DBError         error    `json:",omitempty"` //
}

type SaveConfigDataType

type SaveConfigDataType int
const (
	StringType SaveConfigDataType = 0
	IntType    SaveConfigDataType = 1
	BoolType   SaveConfigDataType = 2
)

type SaveConfigItemType

type SaveConfigItemType struct {
	Name   string
	Value  string
	Ty     SaveConfigDataType
	IValue int64
	BValue bool
}

type ServeMux

type ServeMux struct {
	InOrd         []*MuxEntry   `json:"OrderedPatternList"` // NEW: in order set of patterns
	IsCompiled    bool          `json:"IsCompiled"`         //false when we still need to compile patterns into final matcher.
	RRList        []*MuxRREntry `json:"RRList"`             // List of re-writes to occure beofre match.
	BaseServerUrl string        // Used in generating cURL samles
	// contains filtered or unexported fields
}

ServeMux is an HTTP request multiplexer. It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL.

Patterns name fixed, rooted paths, like "/favicon.ico", or rooted subtrees, like "/images/" (note the trailing slash). Longer patterns take precedence over shorter ones, so that if there are handlers registered for both "/images/" and "/images/thumbnails/", the latter handler will be called for paths beginning "/images/thumbnails/" and the former will receive requests for any other paths in the "/images/" subtree.

Note that since a pattern ending in a slash names a rooted subtree, the pattern "/" matches all paths not matched by other registered patterns, not just the URL with Path == "/".

If a subtree has been registered and a request is received naming the subtree root without its trailing slash, ServeMux redirects that request to the subtree root (adding the trailing slash). This behavior can be overridden with a separate registration for the path without the trailing slash. For example, registering "/images/" causes ServeMux to redirect a request for "/images" to "/images/", unless "/images" has been registered separately.

Patterns may optionally begin with a host name, restricting matches to URLs on that host only. Host-specific patterns take precedence over general patterns, so that a handler might register for the two patterns "/codesearch" and "codesearch.google.com/" without also taking over requests for "http://www.google.com/".

ServeMux also takes care of sanitizing the URL request path and the Host header, stripping the port number and redirecting any request containing . or .. elements or repeated slashes to an equivalent, cleaner URL.

func NewServeMux

func NewServeMux(out io.Writer, gcfg *BaseConfigType) *ServeMux

ok NewServeMux returns a pointer to a ServeMux

func (*ServeMux) Compile

func (mux *ServeMux) Compile()

func (*ServeMux) CompilePB

func (mux *ServeMux) CompilePB(pbDir string)

xyzzy4004 0- placeholder - this will have to be updated to generate ProtoBuf xyzzy4004 - stuff in ./proto directory. xyzzy4004 - Probably add a CLI option --gen-proto-buf ./proto and other --gen options xyzzy4004 - to CLI - with flags passed in. xyzzy4004 - Also --gRPC-host-port HHH,YYY - list of ports to serve protobuf as an interface. xyzzy4004 - See: https://medium.com/pantomath/how-we-use-grpc-to-build-a-client-server-system-in-go-dd20045fa1c2 xyzzy4004 - See: gRPC-server-in-go.html xyzzy4004 - Also --gRPC-REST-host-port HHH,YYY - where to serve the corresponding JSON API - rest server for the gRPC interface.

func (*ServeMux) ConvRRData

func (mux *ServeMux) ConvRRData(www http.ResponseWriter, req *http.Request, mdata map[string]string, vv *MuxRREntry) (rv string)

func (*ServeMux) CreateHandleBulkOperations

func (mux *ServeMux) CreateHandleBulkOperations(gCfg *BaseConfigType) (handle func(www http.ResponseWriter, req *http.Request))

------------------------------------------------------------------------------------------------------------------------------------------

1. Allow for CSV and Excel file formats.
	csv
		API = ??
		Column titles == Name for Data

func (*ServeMux) Desc

func (mux *ServeMux) Desc() (handle func(www http.ResponseWriter, req *http.Request))

func (*ServeMux) DumpPaths

func (mux *ServeMux) DumpPaths()

ok DumpPaths prints out the set of paths that are in the mux. It's only reason for existence is to help a user debug why things are or are not reaching a destination handler.

func (*ServeMux) DumpReplaceRule

func (mux *ServeMux) DumpReplaceRule(fp *os.File)

func (*ServeMux) EndApp

func (mux *ServeMux) EndApp()

End 1 level of SetApp path.

func (*ServeMux) GenCurlSample

func (mux *ServeMux) GenCurlSample(vv *MuxEntry) (rv string)

func (*ServeMux) GenRRCurlSample

func (mux *ServeMux) GenRRCurlSample(vv *MuxRREntry) (rv string)

func (*ServeMux) GenRRUrlPattern

func (mux *ServeMux) GenRRUrlPattern(me *MuxRREntry) (rv string)

func (*ServeMux) GenUrlPattern

func (mux *ServeMux) GenUrlPattern(me *MuxEntry) (rv string)

MatchTo []MuxMatchItem `json:"MatchTo"` // match to a set of items.

func (*ServeMux) GenerateAnalytics

func (mux *ServeMux) GenerateAnalytics() (handle func(www http.ResponseWriter, req *http.Request))

func (*ServeMux) Handle

func (mux *ServeMux) Handle(pattern string, handler http.Handler) (rv *MuxAdditionalCriteria)

Handle registers the handler for the given pattern. If a handler already exists for pattern, Handle panics.

func (*ServeMux) HandleFunc

func (mux *ServeMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))

HandleFunc registers the handler function for the given pattern.

func (*ServeMux) Handler

func (mux *ServeMux) Handler(www http.ResponseWriter, req *http.Request) (h http.Handler, pattern string)

http.Handler returns the handler to use for the given request, consulting r.Method, r.Host, and r.URL.Path. It always returns a non-nil handler. If the path is not in its canonical form, the handler will be an internally-generated handler that redirects to the canonical path. If the host contains a port, it is ignored when matching handlers.

The path and host are used unchanged for CONNECT requests.

http.Handler also returns the registered pattern that matches the request or, in the case of internally-generated redirects, the pattern that will match after following the redirect.

If there is no registered handler that applies to the request, http.Handler returns a “page not found” handler and an empty pattern.

func (*ServeMux) HasRolePriv

func (mux *ServeMux) HasRolePriv(www http.ResponseWriter, req *http.Request, reqAuthPrivs []string) bool

func (*ServeMux) InvalidInputParameterHandler

func (mux *ServeMux) InvalidInputParameterHandler(kk int, e error) http.Handler

func (*ServeMux) IsAuthRequired

func (mux *ServeMux) IsAuthRequired(www http.ResponseWriter, req *http.Request) (AuthReq bool, pattern string, authPrivs []string)

Find out if this path requires authentication

func (*ServeMux) ReplaceRule

func (mux *ServeMux) ReplaceRule(pattern, rTempl string) (rv *MuxRRAdditionalCriteria)

func (*ServeMux) RewriteRequest

func (mux *ServeMux) RewriteRequest(www http.ResponseWriter, req *http.Request, URIComponents []string) (err error)

func (*ServeMux) ServeHTTP

func (mux *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP dispatches the request to the handler whose pattern most closely matches the request URL.

func (*ServeMux) SetApp

func (mux *ServeMux) SetApp(path, name string, cfg ...map[string]interface{}) *MuxAdditionalCriteria

Setting a "grouping" app, like /admin/ or /maint/ or other "APP" by name // SEE: func (mux *ServeMux) Handle(pattern string, handler http.Handler) {

func (*ServeMux) SetDebugFlags

func (mux *ServeMux) SetDebugFlags(DbOn map[string]bool)

SetDebugFlags turns on/off flags that allow for debuging output in this code.

func (*ServeMux) ValidateInputParameters

func (mux *ServeMux) ValidateInputParameters(www http.ResponseWriter, req *http.Request, kInOrd int) (err error)

ValidateInputParameters checks input values for type and value. Also processing of AltNames and Defaults.

func (*ServeMux) ValidateValidationTypeAtCompile

func (mux *ServeMux) ValidateValidationTypeAtCompile(kInOrd int) (err error)

type StatusType

type StatusType int
const (
	OkContinueSaveOutData StatusType = 1
	OkDiscard             StatusType = 2
	ErrorFail             StatusType = 3
)

func ConvGeolocation

func ConvGeolocation(www http.ResponseWriter, req *http.Request, pp PrePostFlag, cfgData, inData string) (outData string, status StatusType, err error)

ConvGeolocation takes a single geolocation string value in the format a,b,c,d and converts it into a set of 8 values.

func ConvQrId

func ConvQrId(www http.ResponseWriter, req *http.Request, pp PrePostFlag, cfgData, inData string) (outData string, status StatusType, err error)

func ConvQrId60

func ConvQrId60(www http.ResponseWriter, req *http.Request, pp PrePostFlag, cfgData, inData string) (outData string, status StatusType, err error)

func PPFlushPrivCache

func PPFlushPrivCache(www http.ResponseWriter, req *http.Request, pp PrePostFlag, cfgData, inData string) (outData string, status StatusType, err error)

type ValidationFunction

type ValidationFunction func(s string, data interface{}, data2 []string) bool

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL