Documentation ¶
Index ¶
- Constants
- Variables
- func AddLanguage(language, translations string)
- func CSVRead(file string) (ret [][]string, err error)
- func CSVReadWtEnc(file, encodingStr string) (ret [][]string, err error)
- func CSVWrite(file string, data [][]string) (err error)
- func CSVWriteNoCreate(file string, data [][]string) error
- func CSVWriteWtEnc(file, encodingStr string, data [][]string) (err error)
- func CSVWriteWtEncNoCreate(file, encodingStr string, data [][]string) (err error)
- func ChkCfmNPrompt(noti, exception string) bool
- func ChooseInts(arr [][]string, notif string) (id int)
- func ChooseMaps(choices []map[string]string, sep string, indI ...string) int
- func ChooseStrings(choices []string) (int, string)
- func ChooseStringsWtIDs(fL func() int, fI func(int) int, fV func(int) string, notif string) (res int)
- func DiffDate(dateO, dateN string) (diff int, err error)
- func EscapeStr4Map(str string) string
- func FileAppend(file string, bytes []byte) (err error)
- func FileDel(fn string) error
- func FileReadByPiece(file string, readSz func(indx uint32, inf fs.FileInfo, done uint32) uint32, ...) (err error)
- func FileReaderByPiece(rdr io.ReadCloser, name string, ...) (err error)
- func FileType(fn string) string
- func FileWrite(file string, bytes []byte) error
- func FileWriteNoCreate(file string, bytes []byte) error
- func FindStrMap(obj interface{}, key string) (interface{}, bool)
- func GetCaller(skip int) string
- func GetCallerLog() string
- func GetCfgDir(vendor, module string) string
- func GetDate(info string) string
- func GetLanguageStr(id string) (string, error)
- func HttpSend(method, url string, bodyReq io.Reader) (*http.Response, error)
- func InitLanguages()
- func InitLogger(out io.Writer) error
- func ListEnc() (ret []string)
- func ListLanguages(fun func(name, id string))
- func LoadLanguage(lang string) (string, error)
- func Log(out ...any)
- func LogFatal(out ...any)
- func LogPrint(out ...any)
- func LogPrintWtTime(out ...any)
- func LogWtTime(out ...any)
- func MakeDbs() (*Dbs, CfgEZtools, error)
- func MakeDbsWtCfgFile(path, file string) (*Dbs, CfgEZtools, error)
- func PromptInt(pi string) (res int, err error)
- func PromptIntStr(pi string, ps string) (i int, s string)
- func PromptPwd(ps string) string
- func PromptStr(ps string) string
- func RangeStrMap(obj interface{}, fun func(k string, v interface{}) bool) bool
- func RestGetBody(resp *http.Response, magic []byte) (bodyType string, bodyBytes []byte, statusCode int, err error)
- func RestParseBody(resp *http.Response, fileName string, strucOut interface{}, magic []byte) (recognized, bodyType string, bodyBytes []byte, statusCode int, err error)
- func RestSend(method, url string, authInfo AuthInfo, bodyReq io.Reader) (*http.Response, error)
- func RestSendFileNHdr(method, url string, authInfo AuthInfo, fType, fName string, ...) (*http.Response, error)
- func RestSendHdr(method, url string, authInfo AuthInfo, bodyReq io.Reader, ...) (*http.Response, error)
- func SetLogFlags(f int)
- func SetLogFunc(f func(...any))
- func ShowArrln(arr []string)
- func ShowByteln(ps []byte)
- func ShowSthln(sth any)
- func ShowStr(ps ...any)
- func ShowStrln(ps ...any)
- func ShowWtFmt(fs string, sth ...any)
- func SqlRows2Strings(rows *sql.Rows) (res [][]string, err error)
- func TranDate(date string) string
- func TranSize(b int64, precision int, space bool) string
- func XMLRead(file string, data interface{}) error
- func XMLReadDefault(path, file string, cfg interface{}) (pathFound string, err error)
- func XMLReader(rdr io.ReadCloser, data interface{}) error
- func XMLWrite(file string, data interface{}, indent string) error
- func XMLWriteDefault(module string, data interface{}, indent string) (pathFound string, err error)
- func XMLWriteNoCreate(file string, data interface{}, indent string) error
- func XMLWriter(wrt io.WriteCloser, data interface{}, indent string) error
- func Zip(files []string, baseDir, zpName string) (ret []error)
- func ZipWtReaderWriter(getRd func() (string, io.ReadCloser), wr io.WriteCloser) (ret []error)
- func ZipWtWriter(files []string, baseDir string, wr io.WriteCloser) (ret []error)
- type AuthInfo
- type CfgEZtools
- type CfgEZtoolsDb
- type CfgEZtoolsMap
- func (cfg CfgEZtoolsMap) Addr2Location(addr string, ...) ([]LocationInfos, []byte, error)
- func (cfg CfgEZtoolsMap) CalcRouteWalk(loc [2]LocationInfos, ...) ([]PathInfos, []byte, error)
- func (cfg CfgEZtoolsMap) CanParseAddr() bool
- func (cfg CfgEZtoolsMap) CanRouteWalk() bool
- func (cfg CfgEZtoolsMap) CanStaticMap(quan int) bool
- func (cfg CfgEZtoolsMap) StaticMap2File(file []string, loc []LocationInfos, ...) (ret error)
- type CfgEZtoolsMapParams
- type CfgEZtoolsMapReply
- type CfgEZtoolsMapStatic
- type CfgEZtoolsMapTypes
- type Dbs
- func (db Dbs) AddPair(table string, id int, str string) (res int, err error)
- func (db Dbs) AddPairNoID(table string, str string) (int, error)
- func (db Dbs) AddWtParams(table string, fields []string, values []string, yes2all bool) (int, error)
- func (db Dbs) AddWtParamsUniq(table string, fields []string, values []string, yes2all bool) (int, error)
- func (db Dbs) AppUpgrade(table, prefix, ver string, server *chan string, ch chan bool)
- func (db Dbs) Authenticate(table, username, password string) error
- func (db Dbs) ChoosePair(table string, allAllowed bool) (int, error)
- func (db Dbs) ChoosePairOrAdd(table string, allAllowed, uniq bool) (int, error)
- func (db Dbs) DeleteWtID(table, id string) error
- func (db Dbs) DeleteWtParams(table, where string, yes2all bool) error
- func (db Dbs) Describe(table string) ([][]string, []string, error)
- func (db Dbs) GetFldID() string
- func (db Dbs) GetFldStr() string
- func (db Dbs) GetMaxID(table string) (int, error)
- func (db Dbs) GetPair(table, id, from, to string) (string, error)
- func (db Dbs) GetPairID(table string, str string) (int, error)
- func (db Dbs) GetPairIDFromInt(table string, val int) (int, error)
- func (db Dbs) GetPairInt(table string, id string) (int, error)
- func (db Dbs) GetPairStr(table string, id string) (string, error)
- func (db Dbs) GetPairStrFromInt(table string, id int) (string, error)
- func (db Dbs) GetSortedPairsIntStr(table string) (ps *Pairs[int, string], err error)
- func (db Dbs) GetTblDef() string
- func (db Dbs) Locate(table string, str string) (id int, err error)
- func (db Dbs) Search(table string, cri string, sel []string, more string) ([][]string, error)
- func (db *Dbs) SetFldDef(id, str string)
- func (db Dbs) ShrinkIDs(table string, fun func(b4, aft string)) error
- func (db Dbs) UpdatePairID(table string, idOld, idNew string) error
- func (db Dbs) UpdatePairWtParams(table string, id, str string) error
- func (db Dbs) UpdateWtParams(table, cri string, fields, values []string, neglectEmpty, yes2all bool) error
- type LocationInfos
- func (loc *LocationInfos) Parse(in interface{}, separator, order string) bool
- func (loc *LocationInfos) ParseLaLo(in interface{}, lalo string) bool
- func (loc *LocationInfos) ParseLevel(types *CfgEZtoolsMapTypes, v any)
- func (loc *LocationInfos) SetLabel(lbl any) bool
- func (loc LocationInfos) String(separator, order string) string
- type Pairs
- func (ps *Pairs[K, V]) Add(key K, val V)
- func (ps *Pairs[K, V]) AddNSort(key K, val V)
- func (ps *Pairs[K, V]) FindKey(s K) (ret V, err error)
- func (ps *Pairs[K, V]) FindVal(s V) (ret K, err error)
- func (ps *Pairs[K, V]) Get(index int) (rK K, rV V, err error)
- func (ps *Pairs[K, V]) GetNMove() (rK K, rV V, err error)
- func (ps Pairs[K, V]) IsSorted() bool
- func (ps Pairs[K, V]) Len() int
- func (ps *Pairs[K, V]) Rewind()
- func (ps *Pairs[K, V]) Set(index int, key K, val V) error
- func (ps *Pairs[K, V]) SetPrev(key K, val V) error
- func (ps *Pairs[K, V]) Sort()
- type PathInfos
Constants ¶
const ( // DefID is the default ID DefID = 0 // AllID stands for all items, which itself is out of valid ID scope AllID = DefID - 1 // InvalidID better to be negative to be different from a normal ID // it is used as indexes into slices, too InvalidID = DefID - 2 //pairs defined some related )
const ( FileCreatePermission = 0644 DirCreatePermission = 0755 FileSizeMax2Split = 2<<31 - 1 FilCpBufSz = 1024 * 1024 )
const ( LOCATION_TYPE_UNKNOWN = iota // areas from larger to smaller LOCATION_TYPE_COUNTRY LOCATION_TYPE_PROVINCE LOCATION_TYPE_CITY LOCATION_TYPE_DISTRICT LOCATION_TYPE_TOWN LOCATION_TYPE_STREET // areas below should be small enough to calculate direction LOCATION_TYPE_CBD LOCATION_TYPE_COMMUNITY LOCATION_TYPE_CROSSING LOCATION_TYPE_POI LOCATION_TYPE_NUMBER LOCATION_TYPE_MAX UNIT_TYPE_M = 1.0 UNIT_TYPE_KM = 1000.0 UNIT_TYPE_SEC = 1.0 / 60.0 UNIT_TYPE_MIN = 1.0 UNIT_TYPE_HOUR = 60.0 // location type strings in configuration file LOCATION_TYPE_STR_UNKNOWN = "unknown" LOCATION_TYPE_STR_COUNTRY = "country" LOCATION_TYPE_STR_PROVINCE = "province" LOCATION_TYPE_STR_CITY = "city" LOCATION_TYPE_STR_DISTRICT = "district" LOCATION_TYPE_STR_TOWN = "town" LOCATION_TYPE_STR_CBD = "cbd" LOCATION_TYPE_STR_POI = "poi" LOCATION_TYPE_STR_STREET = "street" LOCATION_TYPE_STR_CROSSING = "crossing" LOCATION_TYPE_STR_NUMBER = "number" LOCATION_TYPE_STR_COMMUNITY = "community" // UNIT_TYPE_STR_KM is kilometer UNIT_TYPE_STR_KM = "km" // UNIT_TYPE_STR_M is meter. this is default UNIT_TYPE_STR_M = "m" // UNIT_TYPE_STR_HOUR is hour UNIT_TYPE_STR_HOUR = "hour" // UNIT_TYPE_STR_MIN is minute. this is default UNIT_TYPE_STR_MIN = "min" // UNIT_TYPE_STR_SEC is second UNIT_TYPE_STR_SEC = "sec" // reply type strings in configuration file // MAP_REPLY_TYPE_STATUS is OK for results MAP_REPLY_TYPE_STATUS = "status" // MAP_REPLY_TYPE_RESULTS contains sublevel of results MAP_REPLY_TYPE_RESULTS = "results" // MAP_REPLY_TYPE_LEVEL is the level/type of a location MAP_REPLY_TYPE_LEVEL = "level" // MAP_REPLY_TYPE_LEVEL is the level/type of a location MAP_REPLY_TYPE_KNOWN = "known" // MAP_REPLY_TYPE_LOCATION contains location info MAP_REPLY_TYPE_LOCATION = "location" // MAP_REPLY_TYPE_LATI is latitude string in reply MAP_REPLY_TYPE_LATI = "lati" // MAP_REPLY_TYPE_LONGI is longitude string in reply MAP_REPLY_TYPE_LONGI = "long" // MAP_REPLY_TYPE_DISTANCE is the distance between two locations MAP_REPLY_TYPE_DISTANCE = "distance" // MAP_REPLY_TYPE_DURATION is the duration between two locations MAP_REPLY_TYPE_DURATION = "duration" // MAP_REPLY_TYPE_DISTANCE_UNIT is the distance between two locations MAP_REPLY_TYPE_DISTANCE_UNIT = "distanceUnit" // MAP_REPLY_TYPE_DURATION_UNIT is the duration between two locations MAP_REPLY_TYPE_DURATION_UNIT = "durationUnit" MAP_REPLY_STRU_MAP = "map" MAP_REPLY_STRU_MAPSLC = "slicedmap" // PATH_TYPE_STR_WALK is path calculation for walking PATH_TYPE_STR_WALK = "walk" // MAP_LALO_TYPE_STR_LALO = latitude<separator>longitude MAP_LALO_TYPE_STR_LALO = "lalo" // MAP_LALO_TYPE_STR_LALO = longitude<separator>latitude MAP_LALO_TYPE_STR_LOLA = "lola" )
const ( AUTH_NONE = iota AUTH_PLAIN AUTH_BASIC AUTH_DIGEST METHOD_GET = "GET" METHOD_PUT = "PUT" METHOD_POST = "POST" METHOD_DEL = "DELETE" BODY_TYPE_JSON = "json" BODY_TYPE_FILE = "file" BODY_TYPE_TEXT = "text" )
const ( LogFlagDate = log.Ldate LogFlagTime = log.Ltime LogFlagDateNTime = log.LstdFlags LogFlagFile = log.Lshortfile LogFlagDateTimeNFile = LogFlagDateNTime | LogFlagFile )
const (
EncodingGbk = "gbk"
)
Variables ¶
var ( // ErrNoValidResults stands for no valid results ErrNoValidResults = errors.New("no valid results") // ErrOutOfBound stands for out of bound ErrOutOfBound = errors.New("out of bound") // ErrInvalidInput stands for invalid input ErrInvalidInput = errors.New("invalid input") // ErrInExistence stands for result from input already in existence ErrInExistence = errors.New("in existence") // ErrAccess stands for access failure, such as privilege, collision ErrAccess = errors.New("access failure") // ErrAbort stands for abort, such as requesting to exit from UI ErrAbort = errors.New("abort") // ErrIncomplete stands for incomplete results, that is maybe minor ErrIncomplete = errors.New("incomplete results") )
var ( // Debugging marks debugging mode Debugging bool // whether more debug procedures // Verbose marse debugging output level Verbose = 0 // ChoiceNotification is printed when user needs to choose from choices ChoiceNotification = "Your choice is: " )
var AUTH_INSECURE_TLS bool
Functions ¶
func AddLanguage ¶ added in v4.2.0
func AddLanguage(language, translations string)
AddLanguage add a language resource 2*n/4
Example: ID = "translated string"
AddLanguage([]byte(`
StrFlw = "flow" StrAll = "select all" `), "en"))
func CSVReadWtEnc ¶
CSVReadWtEnc reads file into slice of slice of string, with specified encoding
func CSVWriteNoCreate ¶
CSVWriteNoCreate writes data to existing file by a full path (with .csv extension)
func CSVWriteWtEnc ¶
CSVWriteWtEnc writes file with slice of slice of string, with specified encoding
func CSVWriteWtEncNoCreate ¶
CSVWriteWtEncNoCreate writes existing file with slice of slice of string, with specified encoding
func ChkCfmNPrompt ¶
ChkCfmNPrompt checks defaults and return false only when user replied exception program exits when user replied 'q' or 'e' no more confirmations when user replied 'a' or 'c' verbose set when user replied a number, in which case the prompt will show again
All answers taken as lowercase
func ChooseInts ¶
ChooseInts asks user to choose from a slice Parameters. arr[][0]=id. arr[][1]=string
func ChooseMaps ¶
ChooseMaps asks user to choose from a slice of map of string to string parameters: slice.
separator between two piece of information. index(-es) into the map (to be contacted) to be information of each item, or separators between two indexes.
example: (c, ";", "a", "c") with
c index name value 0 a A 0 c C 1 a B 1 c D will print 0: A;C 1: B;D
func ChooseStrings ¶
ChooseStrings asks user to choose from a slice return values: index (InvalidID if not a valid one) and string
func ChooseStringsWtIDs ¶
func ChooseStringsWtIDs(fL func() int, fI func(int) int, fV func(int) string, notif string) (res int)
ChooseStringsWtIDs is for general usage to ask user to choose from a slice or anything parameters.
fL=quantity of elements fI=get index to match user's input fV=get message to show for each index notif=notification string for user
func EscapeStr4Map ¶
EscapeStr4Map reorders Pairs and return a string for preMd5
may be used as preMd5Whole
func FileAppend ¶ added in v4.5.0
FileAppend appends bytes to file
file will be created, if not exists yet, but parent directories cannot be created.
func FileReadByPiece ¶ added in v4.6.0
func FileReadByPiece(file string, readSz func(indx uint32, inf fs.FileInfo, done uint32) uint32, fun func(indx uint32, inf fs.FileInfo, offset uint32, bytes []byte) error) (err error)
FileReadByPiece reads a file by hunk in a loop uint32 is to hold file size, so its max size is 4'294'967'295 Parameters:
readSz() returns how much to read, every time fun() handles the read part, every time, returning whether to stop
Return values:
error from fun() ErrIncomplete if the file is zero sized ErrOutOfBound if the size of the file is too big ErrInvalidInput if the size of the part read does not equal the request from os.Stat(), os.OpenFile(), os.File.Seek(), os.File.Read()
func FileReaderByPiece ¶ added in v4.7.0
func FileReaderByPiece(rdr io.ReadCloser, name string, readSz func(indx uint32, name string) (uint32, string), fun func(indx uint32, name string, bytes []byte, done bool) error) (err error)
FileReaderByPiece reads a file by hunk in a loop Parameters:
func FileWrite ¶
FileWrite writes bytes to file Return value: from os.WriteFile() or os.MkdirAll(), if failed to creat parent directories
func FileWriteNoCreate ¶
FileWriteNoCreate writes input bytes to existing file Return value: from FileWrite() or os.Stat()
func FindStrMap ¶
FindStrMap find string key in map[string]interface{} obj,
returning the value and true or nil and false.
func GetCaller ¶ added in v4.1.0
GetCaller returns caller function:line Parameter: 1 for immediate caller
func GetCallerLog ¶ added in v4.4.0
func GetCallerLog() string
func GetCfgDir ¶ added in v4.2.0
GetCfgDir returns config directory by system Parameters: vendor can be empty
func GetLanguageStr ¶ added in v4.2.0
GetLanguageStr returns translated string by ID 4*n/4
func HttpSend ¶
HttpSend sends HTTP request and returns the result. It does not need AuthInfo as RestSend. Set AUTH_INSECURE_TLS to true to skip TLS (X509) verification
func InitLanguages ¶ added in v4.2.0
func InitLanguages()
InitLanguages initialize resources for i18n 1/4
func ListEnc ¶
func ListEnc() (ret []string)
ListEnc list all valid encoding strings for
CSVReadWtEnc() UTF-8 is default and not listed.
func ListLanguages ¶ added in v4.2.0
func ListLanguages(fun func(name, id string))
ListLanguages loops all translated languages Parameters: name is like "English", id is like "en"
func LoadLanguage ¶ added in v4.2.0
LoadLanguage load language of system 3/4
func LogPrintWtTime ¶
func LogPrintWtTime(out ...any)
LogPrintWtTime logs and prints a string with time
func MakeDbs ¶
func MakeDbs() (*Dbs, CfgEZtools, error)
MakeDb connects to the database using parameters from eztools.xml root element is named "root", elements include "ip", "db", "user" and "pass"
func MakeDbsWtCfgFile ¶
func MakeDbsWtCfgFile(path, file string) (*Dbs, CfgEZtools, error)
MakeDbWtCfgFile connects to the database using paramters from {path}/{file} Parameters: path defaults to ${HOME} and .
file defaults to "eztools.xml"
func PromptIntStr ¶
PromptIntStr prompts user and gets two inputs Return values. zero values are default
func RangeStrMap ¶
RangeStrMap iterate through map[string]interface{} obj, calling fun for
each element recursively. When fun returns true, it stops. false is returned if no element found.
func RestGetBody ¶
func RestGetBody(resp *http.Response, magic []byte) (bodyType string, bodyBytes []byte, statusCode int, err error)
RestGetBody get body from response, stripping magic. Return values: bodyType and statusCode are returned as long as resp is provided.
bodyBytes is nil if Content-Length is 0 in header. ErrInvalidInput=no response input ErrOutOfBound=magic not matched ErrNoValidResults=bad status code (non 2xx) other errors from io.ReadAll()
func RestParseBody ¶
func RestParseBody(resp *http.Response, fileName string, strucOut interface{}, magic []byte) (recognized, bodyType string, bodyBytes []byte, statusCode int, err error)
RestParseBody parses body from response to json or file.
text body is not processed.
Return values: ErrIncomplete=not parsed because type not recognized
other errors are from RestGetBody(), json.Unmarshal() or FileWrite()
func RestSendFileNHdr ¶
func RestSendFileNHdr(method, url string, authInfo AuthInfo, fType, fName string, hdrs map[string]string) (*http.Response, error)
RestSendFileNHdr sends Restful API and returns the result.
Specify a file with name and type to be sent as body, and/or extra headers. If something wrong with the file, a request will be sent without it anyway.
func RestSendHdr ¶ added in v4.8.0
func RestSendHdr(method, url string, authInfo AuthInfo, bodyReq io.Reader, hdrs map[string]string) (*http.Response, error)
RestSendHdr sends Restful API and returns the result. With body and/or extra headers.
func SetLogFlags ¶ added in v4.8.0
func SetLogFlags(f int)
func ShowArrln ¶
func ShowArrln(arr []string)
ShowArrln prints a slice in one line with a line break
func ShowByteln ¶
func ShowByteln(ps []byte)
ShowByteln prints byte slice as string with a line break
func ShowSthln ¶
func ShowSthln(sth any)
ShowSthln prints anything with struct names and a line break
func SqlRows2Strings ¶
SqlRows2Strings returns arrays from rows
func TranDate ¶
TranDate removes minuses from date string return current date if empty string as param
func TranSize ¶
TranSize shows the number as file size format input params: b=number; precision=how many number to keep lower than point;
space=whether a space is put between number and unit
copied from https://programming.guide/go/formatting-byte-size-to-human-readable-format.html
func XMLRead ¶
XMLRead reads file into input structure Return values from os.Stat(), os.ReadFile() and xml.Unmarshal()
func XMLReadDefault ¶
XMLReadDefault reads config file into input structure from
- givenpath,
- or given file name (plus .xml) under one of these dirs, current dir, home dir, or system's config dir. the file name is taken as module name for system's config dir.
Return values: full file name with path
ErrNoValidResults=no file parsable other errors from XMLRead()
func XMLReader ¶ added in v4.3.0
func XMLReader(rdr io.ReadCloser, data interface{}) error
XMLReader reads with reader into input structure rdr is not Close()'d
func XMLWrite ¶
XMLWrite writes file from input structure by a full path (with .xml extension) this reformats the file with indent provided
func XMLWriteDefault ¶ added in v4.2.0
XMLWriteDefault writes file from input structure by a module name for both system config directory and file name home dir and current dir are also candidates in case of failure this reformats the file with indent provided
func XMLWriteNoCreate ¶
XMLWriteNoCreate writes existing file from input structure by a full path (with .xml extension) this reformats the file with indent provided
func XMLWriter ¶ added in v4.3.0
func XMLWriter(wrt io.WriteCloser, data interface{}, indent string) error
XMLWriter writes with writer from input structure wrt is not Close()'d
func Zip ¶ added in v4.10.0
Zip zips files to zpName, with relative directory baseDir
Parameter: baseDir if "", no dir info packed Return value: error to create result file, or, error to each file to be packed and to final closure
func ZipWtReaderWriter ¶ added in v4.10.0
func ZipWtReaderWriter(getRd func() (string, io.ReadCloser), wr io.WriteCloser) (ret []error)
ZipWtReaderWriter zips files iterated by getRd to wr
readers and wr are Close()'ed before returning the last reader must be nil to stop iteration Return value: error to create result file, or, error to each file to be packed and to final closure
func ZipWtWriter ¶ added in v4.10.0
func ZipWtWriter(files []string, baseDir string, wr io.WriteCloser) (ret []error)
ZipWtWriter zips files to wr, with relative directory baseDir
Parameter: baseDir if "", no dir info packed Return value: error to create result file, or, error to each file to be packed and to final closure
Types ¶
type CfgEZtools ¶
type CfgEZtools struct { // Root of the XML Root xml.Name `xml:"eztools"` // Cmt = comments Cmt string `xml:",comment"` // Text is not used Text string `xml:",chardata"` Db CfgEZtoolsDb `xml:"db"` Map []CfgEZtoolsMap `xml:"map"` }
CfgEZtools defines the structure of a predefined config xml
type CfgEZtoolsDb ¶
type CfgEZtoolsDb struct { // Cmt = comments Cmt string `xml:",comment"` // StrUSER name of the user element for DB StrUSER string `xml:"user"` // StrPASS name of the password element for DB StrPASS string `xml:"pass"` // StrIP name of the IP element for DB StrIP string `xml:"ip"` // StrDB name of the database element StrDB string `xml:"name"` // TblDef name of the default table for DB TblDef string `xml:"tblDef"` // Text is not used Text string `xml:",chardata"` }
type CfgEZtoolsMap ¶
type CfgEZtoolsMap struct { Cmt string `xml:",comment"` Name string `xml:"name,attr"` Key string `xml:"key,attr"` KeyName string `xml:"keyName,attr"` Separator string `xml:"separator,attr"` PathOri string `xml:"ori,attr"` PathDst string `xml:"dst,attr"` Md5Key string `xml:"md5Key,attr"` Md5Pref string `xml:"md5Name,attr"` Lalo string `xml:"lalo,attr"` TimeStamp string `xml:"timestamp,attr"` // Text is not used Text string `xml:",chardata"` Locate struct { Cmt string `xml:",comment"` UrlHost string `xml:"urlHost,attr"` UrlPath string `xml:"urlPath,attr"` Addr string `xml:"addr,attr"` Param []CfgEZtoolsMapParams `xml:"param"` Reply []CfgEZtoolsMapReply `xml:"reply"` // Text is not used Text string `xml:",chardata"` } `xml:"locate"` Types CfgEZtoolsMapTypes `xml:"types"` Paths []struct { Cmt string `xml:",comment"` Type string `xml:"type,attr"` Name string `xml:"name,attr"` UrlHost string `xml:"urlHost,attr"` UrlPath string `xml:"urlPath,attr"` Param []CfgEZtoolsMapParams `xml:"param"` Reply []CfgEZtoolsMapReply `xml:"reply"` // Text is not used Text string `xml:",chardata"` } `xml:"path"` Static []CfgEZtoolsMapStatic `xml:"static"` }
func (CfgEZtoolsMap) Addr2Location ¶
func (cfg CfgEZtoolsMap) Addr2Location(addr string, preMd5Params func(Pairs[string, string]) (Pairs[string, string], string), preMd5Whole func(string) string) ([]LocationInfos, []byte, error)
Addr2Location returns location info from address string Parameters:
some maps require addr to be url.QueryEscape()'ed as a param preMd5Params & preMd5Whole are invoked, after all params are read, and to turn params into string, respectively, even if MD5 is not configured
Return values:
body in response returned for error analysis ErrOutOfBound if json fails to parse ErrNoValidResults if not OK in response
func (CfgEZtoolsMap) CalcRouteWalk ¶
func (cfg CfgEZtoolsMap) CalcRouteWalk(loc [2]LocationInfos, preMd5Params func(Pairs[string, string]) (Pairs[string, string], string), preMd5Whole func(string) string) ( []PathInfos, []byte, error)
CalcRouteWalk returns route info between two locations Parameters: preMd5Params & preMd5Whole are invoked, after all params are read,
and to turn params into string, respectively, even if MD5 is not configured
Return values:
ErrOutOfBound if json fails to parse ErrNoValidResults if not OK in response
func (CfgEZtoolsMap) CanParseAddr ¶
func (cfg CfgEZtoolsMap) CanParseAddr() bool
CanParseAddr checks whether a map can parse an address
func (CfgEZtoolsMap) CanRouteWalk ¶
func (cfg CfgEZtoolsMap) CanRouteWalk() bool
CanRouteWalk checks whether a map can calculate route by walk
func (CfgEZtoolsMap) CanStaticMap ¶
func (cfg CfgEZtoolsMap) CanStaticMap(quan int) bool
CanStaticMap checks whether a map is configured to make static maps if quan is non-zero, the map is able to hold that number of label/pushpins if name is non-zero, the map is named, whose text is, as it
func (CfgEZtoolsMap) StaticMap2File ¶
func (cfg CfgEZtoolsMap) StaticMap2File(file []string, loc []LocationInfos, preMd5Params func(Pairs[string, string]) (Pairs[string, string], string), preMd5Whole func(string) string) (ret error)
StaticMap saves a map picture with locations to a file
it tries all static map configured and saves all
Parameters:
size of file should be same as static maps configured, including invalid loc[0] is the center, if center is configured preMd5Params & preMd5Whole are invoked, after all params are read, and to turn params into string, respectively, even if MD5 is not configured
Return value: error is the first error of a map
ErrInvalidInput=not configured ErrOutOfBound=no file saved
type CfgEZtoolsMapParams ¶
type CfgEZtoolsMapReply ¶
type CfgEZtoolsMapStatic ¶
type CfgEZtoolsMapStatic struct { Cmt string `xml:",comment"` Name string `xml:"name,attr"` UrlHost string `xml:"urlHost,attr"` UrlPath string `xml:"urlPath,attr"` Max int `xml:"max,attr"` Param []CfgEZtoolsMapParams `xml:"param"` Labels struct { Cmt string `xml:",comment"` Center string `xml:"center,attr"` Position int `xml:"position,attr"` Separator string `xml:"separator,attr"` Lead string `xml:"lead,attr"` Colon string `xml:"colon,attr"` Text string `xml:",chardata"` } `xml:"labels"` // Text can be used as name for different kinds of maps Text string `xml:",chardata"` }
func (CfgEZtoolsMapStatic) CanStaticMap ¶
func (cfg CfgEZtoolsMapStatic) CanStaticMap(quan int) bool
CanStaticMap checks whether a map is configured to make static maps if quan is non-zero, the map is able to hold that number of label/pushpins
func (CfgEZtoolsMapStatic) StaticMap2File ¶
func (cfg CfgEZtoolsMapStatic) StaticMap2File(cfgM CfgEZtoolsMap, file string, loc []LocationInfos, preMd5Params func(Pairs[string, string]) (Pairs[string, string], string), preMd5Whole func(string) string) ([]byte, error)
StaticMap saves a map picture with locations to a file Parameter: loc[0] is the center Return value:
ErrInvalidInput=not configured ErrOutOfBound=no file saved
type CfgEZtoolsMapTypes ¶
type CfgEZtoolsMapTypes struct { Cmt string `xml:",comment"` // Text is not used Text string `xml:",chardata"` Level []struct { Cmt string `xml:",comment"` Type string `xml:"type,attr"` Text string `xml:",chardata"` } `xml:"level"` Unit []struct { Cmt string `xml:",comment"` Type string `xml:"type,attr"` Text string `xml:",chardata"` } `xml:"unit"` // contains filtered or unexported fields }
type Dbs ¶
func MakeDbsWtCfgs ¶
MakeDbWtCfgs connects to the database using paramters,
and initialize variables with table tblDef
Return value: error = ErrIncomplete when tblDef does not provide
information for variables. use SetFldDef to provide it afterwards.
func (Dbs) AddPairNoID ¶
AddPairNoID adds an item with value, where ID should be auto generated
func (Dbs) AddWtParams ¶
func (db Dbs) AddWtParams(table string, fields []string, values []string, yes2all bool) (int, error)
AddWtParams adds "values" to "fields", no matter whether duplicate records in existence. Parameter yes2all = no confirmation in debug mode. Always no confirmation in non-debug mode.
func (Dbs) AddWtParamsUniq ¶
func (db Dbs) AddWtParamsUniq(table string, fields []string, values []string, yes2all bool) (int, error)
AddWtParamsUniq adds "values" to "fields", if no duplicate records in existence. Parameter yes2all = no confirmation in debug mode. Always no confirmation in non-debug mode.
func (Dbs) AppUpgrade ¶
AppUpgrade checks for updates and applies the update automatically, which will work next time the app is run. Parameters: - table not used yet and is tblDef - Items with following names and **prefix**, in table, are used to check updates
- Url, UrlDev: IP of the update server
- Dir: dir name on the server
- App: app name on the server
- ver: current version
- server: better to be 1 buffered. server info returned, if not null
- ch: better to be 2 buffered. 1st=false, if wrong server URL configured. 2nd=false, if other configurations wrong, or update check fails.
func (Dbs) Authenticate ¶
Authenticate checks whether authenticated. Parameters: table not used yet and is tblDef Return value: nil if true; ErrNoValidResults if no db config for table name
func (Dbs) ChoosePair ¶
ChoosePair asks user to choose from a table by ID - value pairs. Return value: InvalidID and nil, for invalid input
func (Dbs) ChoosePairOrAdd ¶
ChoosePairOrAdd asks user to choose from a table by ID - value pairs,
allowing to add one new.
Return value: InvalidID and nil, for invalid input
func (Dbs) DeleteWtParams ¶
DeleteWtParams deletes items with specified WHERE clause
func (Dbs) Describe ¶
Describe returns all column information e.g., [[id char(50) NO PRI] [ str tinytext YES ]] Return values: all info, column names, error
func (Dbs) GetPair ¶
GetPair gets "to" field whose "from" field equals "id" in "table" When multiple results got, the first one will be taken. return value error = from db.Query;
ErrNoValidResults when no valid results got, and LogErrPrint will be called.
func (Dbs) GetPairID ¶
GetPairID gets ID (int) from value (string) When multiple results got, the first one will be taken.
func (Dbs) GetPairIDFromInt ¶
// GetSortedPairsIntInt returns all sorted Pairs[int,string] from input table
func (db Dbs) GetSortedPairsIntInt(table string) (pi *Pairs[int,string], err error) { pi = new(Pairs[int,string]) err = db.selectSortedPairs(table, func(id, val interface{}, err error) { defer LogErr(err) if err != nil { return } i, ok := id.(int) if !ok { return } v, ok := val.(int) if !ok { return } pi.Add(i, v) }) return }
GetPairIDFromInt gets ID (int) from value (int) When multiple results got, the first one will be taken.
func (Dbs) GetPairInt ¶
GetPairInt gets value (int) from ID (string)
func (Dbs) GetPairStr ¶
GetPairStr gets value (string) from ID (string)
func (Dbs) GetPairStrFromInt ¶
GetPairStrFromInt gets value (string) from ID (int)
func (Dbs) GetSortedPairsIntStr ¶
GetSortedPairsIntStr returns all sorted Pairs[int,string] from input table
func (Dbs) Search ¶
Search gets values of fields "sel" from "table", using "cri" as "WHERE",
with "more" appended to SQL command.
Parameters: more: will not be prefixed with space automatically
func (Dbs) ShrinkIDs ¶ added in v4.10.1
ShrinkIDs reorganizes table with compacted IDs Parameters: fun is called before changing one ID with old and new values
func (Dbs) UpdatePairID ¶
UpdatePairID updates ID
func (Dbs) UpdatePairWtParams ¶
UpdatePairWtParams updates value by ID
func (Dbs) UpdateWtParams ¶
func (db Dbs) UpdateWtParams(table, cri string, fields, values []string, neglectEmpty, yes2all bool) error
UpdateWtParams updates "fields" in "table" with "values", using "cri" as "WHERE". Parameter yes2all = no confirmation in debug mode. Always no confirmation in non-debug mode. Return values:
ErrInvalidInput if no fields/values as parameters ErrAbort if user chooese no when yes2all is true ErrNoValidResults if no update command can be constructed other errors from sql
type LocationInfos ¶
type LocationInfos struct { // there may be more members in this struct, // so use member names during instance creation Latitude, Longitude float32 Type int Label, TypeStr string }
func (*LocationInfos) Parse ¶
func (loc *LocationInfos) Parse(in interface{}, separator, order string) bool
Parse parses latitude and longitude Parameter:
if in is string, is needs to be like <l1><separator><l2>, l1/l2=latitude/longitude otherwise, in can be a slice, containing two strings or floats
func (*LocationInfos) ParseLaLo ¶
func (loc *LocationInfos) ParseLaLo(in interface{}, lalo string) bool
ParseLaLo sets a string or float64 to latitude or longitude
func (*LocationInfos) ParseLevel ¶
func (loc *LocationInfos) ParseLevel(types *CfgEZtoolsMapTypes, v any)
ParseLevel parses level/type from string or float64
TypeStr is set to the string value, Type is set to recognized level/type, or, LOCATION_TYPE_UNKNOWN if the string is not configured for the map LOCATION_TYPE_MAX if the config string is not in code, which is a critical coding issue
func (*LocationInfos) SetLabel ¶
func (loc *LocationInfos) SetLabel(lbl any) bool
SetLabel sets label for a location Return value: whether set
func (LocationInfos) String ¶
func (loc LocationInfos) String(separator, order string) string
type Pairs ¶
type Pairs[K constraints.Ordered, V comparable] struct { // contains filtered or unexported fields }
Pairs contains key-value pairs. Key needs to be orderable so that Sort() works Value needs to be comparable so that FindVal() works
func ReorderParams4Map ¶
ReorderParams4Map reorders Pairs and return a string for preMd5
may be used as preMd5Params
func (*Pairs[K, V]) Add ¶
func (ps *Pairs[K, V]) Add(key K, val V)
Add appends values to the collection,
moving cursor to the end
func (*Pairs[K, V]) AddNSort ¶
func (ps *Pairs[K, V]) AddNSort(key K, val V)
AddNSort appends values to the collection and sorts it,
moving cursor to the end
func (*Pairs[K, V]) FindKey ¶
FindId find the first value whose **key** matches input
moving cursor to the next of it
Return value:
ErrOutOfBound if collection is empty ErrNoValidResults when none found
func (*Pairs[K, V]) FindVal ¶
FindStr find the first key whose **value** matches input
moving cursor to the next of it
Return value:
ErrOutOfBound if collection is empty ErrNoValidResults when none found
func (*Pairs[K, V]) Get ¶
Get get values of an ellement in the collection cursor moves to the next of it Return value:
ErrOutOfBound if collection is empty or index is not valid
func (*Pairs[K, V]) GetNMove ¶
Next gets the current item in the collection and moves to the next
call Rewind() after Add() to reset to and get the first item
Return value:
ErrOutOfBound if collection is exhausted
func (*Pairs[K, V]) Rewind ¶
func (ps *Pairs[K, V]) Rewind()
Rewind used after Add() to reset and before GetNMove() to the first item
func (*Pairs[K, V]) Set ¶
Set sets values of an ellement in the collection cursor moves to the next of it this makes the collection unsorted Return value:
ErrOutOfBound if collection is empty or index is not valid
type PathInfos ¶
type PathInfos struct { // there may be more members in this struct, // so use member names during instance creation Distance, Duration float32 UnitDistance, UnitDuration float32 }
func (*PathInfos) ParseUnit ¶
func (path *PathInfos) ParseUnit(types CfgEZtoolsMapTypes, v interface{}) (ret float32)