eztools

package module
v6.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2023 License: Apache-2.0 Imports: 43 Imported by: 4

README

EZ Tools

source files

constants - consts.go

ID's and error values.

internationalization - i18n.go

Language resource usages.

command line / logging - ui.go

Debugging and Verbose to control interaction and verbose levels.

file I/O - files.go

File I/O and zips.

Csv/Xml - cfg.go

It reads/writes from/to a file. Saving an XML may reorganize its structure according to parsed data and lose some unrecognized!

app self-update - appup.go

It gets server info from database and updates in background. The next time the app is run, it will be in the new version.

LDAP - auth.go

It gets server info, including DN structure, from database and tries to bind to check for authentication.

pair structures - pair.go

Sturctures of pairs of int and string.

databases (SQL) - db.go

It provides operations to connect, insert, search from databases.

HTTP - http.go

Use this to send and receive HTTP. Mainly based on the needs for Restful APIs,
such as Bugzilla, Jira, Gerrit and Jenkins.

map usages - map.go

Use this to parse location info from a string, calculate distance between two locations by walk, or generate static maps.
Baidu, Amap, QQ & Bing tested and configurations provided in sample xml. Labeled static maps of QQ and address parsing of Bing in Beijing does not generate correct results.

config file - sample.xml to be customized to eztools.xml

Better to be under current or home directory. File name customizable.

  • eztools root
    • db element
      • ip, name, user, pass: IP, database name, user name, password of the database
      • tblDef: table name of the main table, as chore below
    • map elements
      • name attribute: name of a map
      • key attribute: main key from provider
      • separator attribute: separator between latitude and longitude
      • ori attribute: origin string
      • dst attribute: destination string
      • lalo attribute: order of position numbers. lalo=latitude and longitude; lola=longitude and latitude
      • timestamp attribute: timestamp string, if required, which adds timestamp to requests
      • md5Key attribute: key to calculate MD5 of requests, if required, which adds MD5 to requests
      • md5Pref attribute: string of MD5 in requests, if required, which adds MD5 to requests
      • types element
        • level elements to match strings of levels/types of positions in a response to our types
        • type attribute: "country", "province", "city", "district", "town", "cbd", "poi", "street", "crossing", "number" or "unknown"
        • data/text is the name string in a response, matching our type
      • locate element for location requests
        • urlHost attribute: first part of URL of requests, excluded from MD5
        • urlPath attribute: latter part of URL of requests, included in MD5
        • addr attribute: address string
        • reply elements to analyze replies
          • name attribute: name string in a response
          • stru attribute: "map"=map (default); "slicedmap"=slice of maps
          • type attribute: "status"=general response code; "results"=a container of results we are interested in; "level"=level/type of the position; "location"=location of latitude and longitude; "known"=formatted address; "lati"=latitude; "long"=longitude
          • some elements needs data/text. Successful code in status replies.
      • path element for path requests
        • urlHost attribute
        • urlPath attribute
        • type attribute: "walk"=by walk
        • param elements
          • name attribute: name of a param in request
          • data/text: value of a param in request
        • reply elements
          • name attribute: name string in a response
          • stru attribute: "map"/"slicedmap"
          • type attribute: "status"=general response code; "results"=a container of results we are interested in; "distance"=distance; "duration"=duration
          • some elements needs data
      • static elements for static maps
        • urlHost attribute
        • urlPath attribute
        • max attribute: max number of labels
        • name attribute: name of the static map config
        • param elements
          • name attribute: name of a param in request
          • max attribute: max value of the param, as a guidance
          • data/text: value of a param in request
        • labels elements
          • center attribute: name string of center of the map in a response
          • lead attribute: value string after label, before other part in a response
          • separator attribute: separator between labels in a response
          • colon attribute: separator between label name and location values in a response
          • position attribute: position of label value in a response.
            0, default: labels={lead}{label name}{colon}{latitude}{map.separator}{longitude}
            2: labels={lead}{latitude}{map.separator}{longitude}{colon}{label name}
          • data/text: name of the label string in a request

main table - chore

It must contains at least two columns. The first is primary key, whose name is also used as id field for other tables. The name of the second is used as str field for other tables. In this way, other tables can use these two field easily. Values of id field should be generated automatically.
Database name customizable.

CREATE TABLE chore (id CHAR(50) NOT NULL UNIQUE, str TINYTEXT, PRIMARY KEY(id)); 
field comment example
id a string for name Ver
str a string for value 1.0

table details

chore's ids

  • Fld*: field names for other tables
  • Tbl*: table names for other tables
  • AuthIP: IP of authentication server
  • AuthRootD: former part of root bind dn before user name
  • AuthRootN: latter part of root bind dn after user name

Documentation

Index

Constants

View Source
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
	// EzpName project name
	EzpName = "EZ Project"
	// EzpURL homepage of project
	EzpURL = "https://ezproject.sourceforge.io/"
)
View Source
const (
	// FileCreatePermission 0644
	FileCreatePermission = 0644
	// DirCreatePermission 0755
	DirCreatePermission = 0755
	// FileSizeMax2Split size of a file piece
	FileSizeMax2Split = 2<<31 - 1
)
View Source
const (
	// HTMLHead head recommented by W3C
	HTMLHead = `` /* 141-byte string literal not displayed */

	// AuthNone no auth in cfg
	AuthNone = iota
	// AuthPlain token
	AuthPlain
	// AuthBasic plain text
	AuthBasic
	// AuthDigest digest
	AuthDigest
	// BodyTypeJSON json
	BodyTypeJSON = "json"
	// MimeTypeJSON full mime type for BodyTypeJSON
	MimeTypeJSON = "application/" + BodyTypeJSON
	// BodyTypeFile file
	BodyTypeFile = "file"
	// MimeTypeFile full mime type for BodyTypeFile
	MimeTypeFile = BodyTypeFile
	// BodyTypeText text
	BodyTypeText = "text"
	// MimeTypeText full mime type for BodyTypeText
	MimeTypeText = BodyTypeText
	// BodyTypeXML xml
	BodyTypeXML = "xml"
	// MimeTypeXML full mime type for BodyTypeXML
	MimeTypeXML = "application/" + BodyTypeXML
	// BodyTypeHTML html
	BodyTypeHTML = "html"
	// MimeTypeHTML full mime type for BodyTypeHTML
	MimeTypeHTML = "text/" + BodyTypeHTML
	// BodyTypeForm form
	BodyTypeForm = "form"
	// MimeTypeForm mime type for BodyTypeForm
	MimeTypeForm = "application/x-www-form-urlencoded"
)
View Source
const (
	// LocationTypeUnknown unknown
	LocationTypeUnknown = iota

	// LocationTypeCountry country
	LocationTypeCountry
	// LocationTypeProvince province
	LocationTypeProvince
	// LocationTypeCity city
	LocationTypeCity
	// LocationTypeDistrict district
	LocationTypeDistrict
	// LocationTypeTown town
	LocationTypeTown
	// LocationTypeStreet street
	LocationTypeStreet

	// LocationTypeCbd CBD
	LocationTypeCbd
	// LocationTypeCommunity community
	LocationTypeCommunity
	// LocationTypeCrossing crossing
	LocationTypeCrossing
	// LocationTypePoi POI
	LocationTypePoi
	// LocationTypeNumber number
	LocationTypeNumber
	// LocationTypeMax quantity of location types
	LocationTypeMax

	// UnitTypeM factor for meters
	UnitTypeM = 1.0
	// UnitTypeKm factor for kilometers
	UnitTypeKm = 1000.0
	// UnitTypeSec factor for seconds
	UnitTypeSec = 1.0 / 60.0
	// UnitTypeMin factor for minutes
	UnitTypeMin = 1.0
	// UnitTypeHour factor for hours
	UnitTypeHour = 60.0

	// LocationTypeStrUnknown location type strings in configuration file
	LocationTypeStrUnknown = "unknown"
	// LocationTypeStrCountry location type strings in configuration file
	LocationTypeStrCountry = "country"
	// LocationTypeStrProvince location type strings in configuration file
	LocationTypeStrProvince = "province"
	// LocationTypeStrCity location type strings in configuration file
	LocationTypeStrCity = "city"
	// LocationTypeStrDistrict location type strings in configuration file
	LocationTypeStrDistrict = "district"
	// LocationTypeStrTown location type strings in configuration file
	LocationTypeStrTown = "town"
	// LocationTypeStrCbd location type strings in configuration file
	LocationTypeStrCbd = "cbd"
	// LocationTypeStrPoi location type strings in configuration file
	LocationTypeStrPoi = "poi"
	// LocationTypeStrStreet location type strings in configuration file
	LocationTypeStrStreet = "street"
	// LocationTypeStrCrossing location type strings in configuration file
	LocationTypeStrCrossing = "crossing"
	// LocationTypeStrNumber location type strings in configuration file
	LocationTypeStrNumber = "number"
	// LocationTypeStrCommunity location type strings in configuration file
	LocationTypeStrCommunity = "community"

	// UnitTypeStrKm is kilometer
	UnitTypeStrKm = "km"
	// UnitTypeStrM is meter. this is default
	UnitTypeStrM = "m"
	// UnitTypeStrHour is hour
	UnitTypeStrHour = "hour"
	// UnitTypeStrMin is minute. this is default
	UnitTypeStrMin = "min"
	// UnitTypeStrSec is second
	UnitTypeStrSec = "sec"

	// MapReplyTypeStatus is OK for results
	MapReplyTypeStatus = "status"
	// MapReplyTypeResults contains sublevel of results
	MapReplyTypeResults = "results"
	// MapReplyTypeLevel is the level/type of a location
	MapReplyTypeLevel = "level"
	// MapReplyTypeKnown is the level/type of a location
	MapReplyTypeKnown = "known"
	// MapReplyTypeLocation contains location info
	MapReplyTypeLocation = "location"
	// MapReplyTypeLati is latitude string in reply
	MapReplyTypeLati = "lati"
	// MapReplyTypeLongi is longitude string in reply
	MapReplyTypeLongi = "long"

	// MapReplyTypeDistance is the distance between two locations
	MapReplyTypeDistance = "distance"
	// MapReplyTypeDuration is the duration between two locations
	MapReplyTypeDuration = "duration"
	// MapReplyTypeDistanceUnit is the distance between two locations
	MapReplyTypeDistanceUnit = "distanceUnit"
	// MapReplyTypeDurationUnit is the duration between two locations
	MapReplyTypeDurationUnit = "durationUnit"

	// MapReplyStruMap map definition in config
	MapReplyStruMap = "map"
	// MapReplyStruMapslc slice definition in config
	MapReplyStruMapslc = "slicedmap"

	// PathTypeStrWalk is path calculation for walking
	PathTypeStrWalk = "walk"

	// MapLaloTypeStrLalo = latitude<separator>longitude
	MapLaloTypeStrLalo = "lalo"
	// MapLaloTypeStrLola = longitude<separator>latitude
	MapLaloTypeStrLola = "lola"
)
View Source
const (

	// LogFlagDate logs with date
	LogFlagDate = log.Ldate
	// LogFlagTime logs with time
	LogFlagTime = log.Ltime
	// LogFlagDateNTime logs with date and time
	LogFlagDateNTime = log.LstdFlags
	// LogFlagFile logs with file name
	LogFlagFile = log.Lshortfile
	// LogFlagDateTimeNFile logs with date, time and file name
	LogFlagDateTimeNFile = LogFlagDateNTime | LogFlagFile
)
View Source
const (
	// EncodingGbk gbk
	EncodingGbk = "gbk"
)

Variables

View Source
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")
)
View Source
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: "
)
View Source
var AuthInsecureTLS bool

AuthInsecureTLS insecure TLS enabled

Functions

func AddLanguage

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 CSVRead

func CSVRead(file string) (ret [][]string, err error)

CSVRead reads UTF-8 file into slice of slice of string

func CSVReadWtEnc

func CSVReadWtEnc(file, encodingStr string) (ret [][]string, err error)

CSVReadWtEnc reads file into slice of slice of string, with specified encoding

func CSVWrite

func CSVWrite(file string, data [][]string) (err error)

CSVWrite writes UTF-8 file with slice of slice of string

func CSVWriteNoCreate

func CSVWriteNoCreate(file string, data [][]string) error

CSVWriteNoCreate writes data to existing file by a full path (with .csv extension)

func CSVWriteWtEnc

func CSVWriteWtEnc(file, encodingStr string, data [][]string) (err error)

CSVWriteWtEnc writes file with slice of slice of string, with specified encoding

func CSVWriteWtEncNoCreate

func CSVWriteWtEncNoCreate(file, encodingStr string, data [][]string) (err error)

CSVWriteWtEncNoCreate writes existing file with slice of slice of string, with specified encoding

func ChkCfmNPrompt

func ChkCfmNPrompt(noti, exception string) bool

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

func ChooseInts(arr [][]string, notif string) (id int)

ChooseInts asks user to choose from a slice Parameters. arr[][0]=id. arr[][1]=string

func ChooseMaps

func ChooseMaps(choices []map[string]string, sep string, indI ...string) int

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

func ChooseStrings(choices []string) (int, string)

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 DiffDate

func DiffDate(dateO, dateN string) (diff int, err error)

DiffDate = dateN - dateO return values: difference in days

func EscapeStr4Map

func EscapeStr4Map(str string) string

EscapeStr4Map reorders Pairs and return a string for preMd5

may be used as preMd5Whole

func FileAppend

func FileAppend(file string, bytes []byte) (err error)

FileAppend appends bytes to file

file will be created, if not exists yet, but parent directories cannot be created.

func FileDel

func FileDel(fn string) error

FileDel file deletion

func FileReadByPiece

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

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 FileType

func FileType(fn string) string

FileType returns MIME type of a file by extension

func FileWrite

func FileWrite(file string, bytes []byte) error

FileWrite writes bytes to file Return value: from os.WriteFile() or os.MkdirAll(), if failed to creat parent directories

func FileWriteNoCreate

func FileWriteNoCreate(file string, bytes []byte) error

FileWriteNoCreate writes input bytes to existing file Return value: from FileWrite() or os.Stat()

func FindStrMap

func FindStrMap(obj interface{}, key string) (interface{}, bool)

FindStrMap find string key in map[string]interface{} obj, returning the value and true or nil and false.

func FormatMimeType

func FormatMimeType(bodyType string) string

FormatMimeType generates MIME type with default params charset=utf-8

func GetCaller

func GetCaller(skip int) string

GetCaller returns caller function:line Parameter: 1 for immediate caller

func GetCallerLog

func GetCallerLog() (ret string)

GetCallerLog returns caller string for Log*

func GetCfgDir

func GetCfgDir(vendor, module string) string

GetCfgDir returns config directory by system Parameters: vendor can be empty

func GetDate

func GetDate(info string) string

GetDate asks user to input a date string

func GetLanguageStr

func GetLanguageStr(id string) (string, error)

GetLanguageStr returns translated string by ID 4*n/4

func HTTPGetBody

func HTTPGetBody(resp *http.Response, magic []byte) (bodyType string,
	bodyBytes []byte, statusCode int, err error)

HTTPGetBody 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 HTTPParseBody

func HTTPParseBody(resp *http.Response, fileName string, strucOut interface{},
	magic []byte) (recognized, bodyType string, bodyBytes []byte, statusCode int, err error)

HTTPParseBody parses body from response to json or file. text body is not processed.

Parameter:

strucOut: func(n *html.Node) for BodyTypeHTML

Return values: ErrIncomplete=not parsed because type not recognized

other errors are from HTTPGetBody(), json.Unmarshal() or FileWrite()

func HTTPSend

func HTTPSend(method, url, bodyType string, bodyReq io.Reader) (*http.Response, error)

HTTPSend sends HTTP request and returns the result. It does not need AuthInfo as HTTPSend. Set AUTH_INSECURE_TLS to true to skip TLS (X509) verification

func HTTPSendAuth

func HTTPSendAuth(method, url, bodyType string, authInfo AuthInfo,
	bodyReq io.Reader) (*http.Response, error)

HTTPSendAuth sends a request and returns the result. = HttpSend + AuthInfo

func HTTPSendAuthNHdr

func HTTPSendAuthNHdr(method, url, bodyType string, authInfo AuthInfo,
	bodyReq io.Reader, hdrs map[string]string) (*http.Response, error)

HTTPSendAuthNHdr sends a request and returns the result. With body and/or extra headers.

func HTTPSendAuthNHdrNFile

func HTTPSendAuthNHdrNFile(method, url string, authInfo AuthInfo,
	fType, fName string, hdrs map[string]string) (*http.Response, error)

HTTPSendAuthNHdrNFile sends a request 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 HTTPSendHdr

func HTTPSendHdr(method, url, bodyType string,
	bodyReq io.Reader, hdrs map[string]string) (*http.Response, error)

HTTPSendHdr sends a request and returns the result. With body and/or extra headers.

func InitLanguages

func InitLanguages()

InitLanguages initialize resources for i18n 1/4

func InitLogger

func InitLogger(out io.Writer) error

InitLogger opens log file

func ListEnc

func ListEnc() (ret []string)

ListEnc list all valid encoding strings for

	CSVReadWtEnc()
 UTF-8 is default and not listed.

func ListLanguages

func ListLanguages(fun func(name, id string))

ListLanguages loops all translated languages Parameters: name is like "English", id is like "en"

func LoadLanguage

func LoadLanguage(lang string) (string, error)

LoadLanguage load language of system 3/4

func Log

func Log(out ...any)

Log logs it

func LogFatal

func LogFatal(out ...any)

LogFatal logs and prints it and exits

func LogPrint

func LogPrint(out ...any)

LogPrint logs and prints it

func LogPrintWtTime

func LogPrintWtTime(out ...any)

LogPrintWtTime logs and prints a string with time

func LogWtTime

func LogWtTime(out ...any)

LogWtTime logs a string with time

func MakeDb

func MakeDb() (*Db, Cfg, error)

MakeDb connects to the database using parameters from eztools.xml root element is named "root", elements include "ip", "db", "user" and "pass"

func MakeDbWtCfgFile

func MakeDbWtCfgFile(path, vendorPath, modulePath, additionalPath, filename string) (*Db, Cfg, error)

MakeDbWtCfgFile connects to the database using paramters from {path}/{file} Parameters: path defaults to ${HOME} and .

func ParseMimeType

func ParseMimeType(v string) string

ParseMimeType parses MIME type to BodyType, neglecting params

func PromptInt

func PromptInt(pi string) (res int, err error)

PromptInt prompts user and gets input Return values. zero values are default

func PromptIntStr

func PromptIntStr(pi string, ps string) (i int, s string)

PromptIntStr prompts user and gets two inputs Return values. zero values are default

func PromptPwd

func PromptPwd(ps string) string

PromptPwd prompts user and get password

func PromptStr

func PromptStr(ps string) string

PromptStr prompts user and get input

func RangeStrMap

func RangeStrMap(obj interface{}, fun func(k string, v interface{}) bool) bool

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 SQLRows2Strings

func SQLRows2Strings(rows *sql.Rows) (res [][]string, err error)

SQLRows2Strings returns arrays from rows

func SetLogFlags

func SetLogFlags(f int)

SetLogFlags sets logging with LogFlag*

func SetLogFunc

func SetLogFunc(f func(...any))

SetLogFunc sets function for all Log*()

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 ShowStr

func ShowStr(ps ...any)

ShowStr prints anything with no line breaks

func ShowStrln

func ShowStrln(ps ...any)

ShowStrln prints anything with a line break

func ShowWtFmt

func ShowWtFmt(fs string, sth ...any)

ShowWtFmt prints with format string like printf

func TranDate

func TranDate(date string) string

TranDate removes minuses from date string return current date if empty string as param

func TranSize

func TranSize(b int64, precision int, space bool) string

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

func XMLRead(file string, data interface{}) error

XMLRead reads file into input structure Return values from os.Stat(), os.ReadFile() and xml.Unmarshal()

func XMLReadDefault

func XMLReadDefault(path, vendor, module, additional, filename string,
	cfg interface{}) (ret string, errs []error)

XMLReadDefault reads config file into input structure from

  1. path,
  2. or given file name (plus .xml) under one of these dirs, current dir, home dir, or {system-app-local-dir}/{vendor}/{module}/{additional} defaults: vendor="", module={filename}, additional="", filename must not be empty.

Return values: ret=full file name with path errs=nil or, if no {file} provided, ret="" errs=ErrInvalidInput or, in case of all failures ret=file paths not found, separated by commas errs=errors from XMLRead() matching all paths

func XMLReader

func XMLReader(rdr io.ReadCloser, data interface{}) error

XMLReader reads with reader into input structure rdr is not Close()'d

func XMLWrite

func XMLWrite(file string, data interface{}, indent string) error

XMLWrite writes file from input structure by a full path (with .xml extension) this reformats the file with indent provided

func XMLWriteDefault

func XMLWriteDefault(vendor, module, additional, filename string,
	data interface{}, indent string) (ret string, err []error)

XMLWriteDefault writes file from input structure this reformats the file with indent provided refer to XMLReadDefault() for parameters and return values.

func XMLWriteNoCreate

func XMLWriteNoCreate(file string, data interface{}, indent string) error

XMLWriteNoCreate writes existing file from input structure by a full path (with .xml extension) this reformats the file with indent provided

func XMLWriter

func XMLWriter(wrt io.WriteCloser, data interface{}, indent string) error

XMLWriter writes with writer from input structure wrt is not Close()'d

func Zip

func Zip(files []string, baseDir, zpName string) (ret []error)

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

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

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 AuthInfo

type AuthInfo struct {
	Type       int
	User, Pass string
}

AuthInfo authorization info

type Cfg

type Cfg 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
	Db CfgDb `xml:"db"`
	// Map cfg of maps
	Map []CfgMap `xml:"map"`
}

Cfg defines the structure of a predefined config xml

type CfgDb

type CfgDb struct {
	// Cmt = comments
	Cmt string `xml:",comment"`
	// Usr name of the user element for DB
	Usr string `xml:"user"`
	// Pas name of the password element for DB
	Pas string `xml:"pass"`
	// IP name of the IP element for DB
	IP string `xml:"ip"`
	// Db name of the database element
	Db string `xml:"name"`
	// TblDef name of the default table for DB
	TblDef string `xml:"tblDef"`
	// Tex = text. not used
	Tex string `xml:",chardata"`
}

CfgDb cfg db

type CfgMap

type CfgMap 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   []CfgMapParams `xml:"param"`
		Reply   []CfgMapReply  `xml:"reply"`
		// Text is not used
		Text string `xml:",chardata"`
	} `xml:"locate"`
	Types CfgMapTypes `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   []CfgMapParams `xml:"param"`
		Reply   []CfgMapReply  `xml:"reply"`
		// Text is not used
		Text string `xml:",chardata"`
	} `xml:"path"`
	Static []CfgMapStatic `xml:"static"`
}

CfgMap map config

func (CfgMap) Addr2Location

func (cfg CfgMap) Addr2Location(addr string,
	preMd5Params func(Pairs[string, string]) (Pairs[string, string], string),
	preMd5Whole func(string) string) ([]LocationInfo, []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 (CfgMap) CalcRouteWalk

func (cfg CfgMap) CalcRouteWalk(loc [2]LocationInfo,
	preMd5Params func(Pairs[string, string]) (Pairs[string, string], string),
	preMd5Whole func(string) string) (
	[]PathInfo, []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 (CfgMap) CanParseAddr

func (cfg CfgMap) CanParseAddr() bool

CanParseAddr checks whether a map can parse an address

func (CfgMap) CanRouteWalk

func (cfg CfgMap) CanRouteWalk() bool

CanRouteWalk checks whether a map can calculate route by walk

func (CfgMap) CanStaticMap

func (cfg CfgMap) 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 (CfgMap) StaticMap2File

func (cfg CfgMap) StaticMap2File(file []string, loc []LocationInfo,
	preMd5Params func(Pairs[string, string]) (Pairs[string, string], string),
	preMd5Whole func(string) string) (ret error)

StaticMap2File 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 CfgMapParams

type CfgMapParams struct {
	Cmt  string `xml:",comment"`
	Name string `xml:"name,attr"`
	Max  string `xml:"max,attr"`
	Min  string `xml:"min,attr"`
	Text string `xml:",chardata"`
}

CfgMapParams params of a map in cfg

type CfgMapReply

type CfgMapReply struct {
	Cmt   string        `xml:",comment"`
	Type  string        `xml:"type,attr"`
	Name  string        `xml:"name,attr"`
	Stru  string        `xml:"stru,attr"`
	Reply []CfgMapReply `xml:"reply"`
	Text  string        `xml:",chardata"`
}

CfgMapReply struct of a reply

type CfgMapStatic

type CfgMapStatic 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   []CfgMapParams `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"`
}

CfgMapStatic map static cfg

func (CfgMapStatic) CanStaticMap

func (cfg CfgMapStatic) 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 (CfgMapStatic) StaticMap2File

func (cfg CfgMapStatic) StaticMap2File(cfgM CfgMap,
	file string, loc []LocationInfo,
	preMd5Params func(Pairs[string, string]) (Pairs[string, string], string),
	preMd5Whole func(string) string) ([]byte, error)

StaticMap2File 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 CfgMapTypes

type CfgMapTypes 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
}

CfgMapTypes map type config

type Db

type Db struct {
	*sql.DB
	// contains filtered or unexported fields
}

Db unified struct for all kinds of dbs, sql only now.

func MakeDbWtCfgs

func MakeDbWtCfgs(user, pass, ip, database, tblDef string) (*Db, error)

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 (Db) AddPair

func (db Db) AddPair(table string, id int, str string) (res int, err error)

AddPair adds an item with ID and value

func (Db) AddPairNoID

func (db Db) AddPairNoID(table string, str string) (int, error)

AddPairNoID adds an item with value, where ID should be auto generated

func (Db) AddWtParams

func (db Db) 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 (Db) AddWtParamsUniq

func (db Db) 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 (Db) AppUpgrade

func (db Db) AppUpgrade(table, prefix, ver string, server *chan string, ch chan bool)

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 (Db) Authenticate

func (db Db) Authenticate(table, username, password string) error

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 (Db) ChoosePair

func (db Db) ChoosePair(table string, allAllowed bool) (int, error)

ChoosePair asks user to choose from a table by ID - value pairs. Return value: InvalidID and nil, for invalid input

func (Db) ChoosePairOrAdd

func (db Db) ChoosePairOrAdd(table string, allAllowed, uniq bool) (int, error)

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 (Db) DeleteWtID

func (db Db) DeleteWtID(table, id string) error

DeleteWtID by ID

func (Db) DeleteWtParams

func (db Db) DeleteWtParams(table, where string, yes2all bool) error

DeleteWtParams deletes items with specified WHERE clause

func (Db) Describe

func (db Db) Describe(table string) ([][]string, []string, error)

Describe returns all column information e.g., [[id char(50) NO PRI] [ str tinytext YES ]] Return values: all info, column names, error

func (Db) GetFldID

func (db Db) GetFldID() string

GetFldID gets field id value

func (Db) GetFldStr

func (db Db) GetFldStr() string

GetFldStr gets field str value

func (Db) GetMaxID

func (db Db) GetMaxID(table string) (int, error)

GetMaxID gets the largest ID in a table.

func (Db) GetPair

func (db Db) GetPair(table, id, from, to string) (string, error)

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 (Db) GetPairID

func (db Db) GetPairID(table string, str string) (int, error)

GetPairID gets ID (int) from value (string) When multiple results got, the first one will be taken.

func (Db) GetPairIDFromInt

func (db Db) GetPairIDFromInt(table string, val int) (int, error)

GetPairIDFromInt gets ID (int) from value (int) When multiple results got, the first one will be taken.

func (Db) GetPairInt

func (db Db) GetPairInt(table string, id string) (int, error)

GetPairInt gets value (int) from ID (string)

func (Db) GetPairStr

func (db Db) GetPairStr(table string, id string) (string, error)

GetPairStr gets value (string) from ID (string)

func (Db) GetPairStrFromInt

func (db Db) GetPairStrFromInt(table string, id int) (string, error)

GetPairStrFromInt gets value (string) from ID (int)

func (Db) GetSortedPairsIntStr

func (db Db) GetSortedPairsIntStr(table string) (ps *Pairs[int, string], err error)

GetSortedPairsIntStr returns all sorted Pairs[int,string] from input table

func (Db) GetTblDef

func (db Db) GetTblDef() string

GetTblDef gets value of a tblDef config

func (Db) Locate

func (db Db) Locate(table string, str string) (id int, err error)

Locate gets ID (int) from value (string) Deprecated: Use GetPairID instead.

func (Db) Search

func (db Db) Search(table string, cri string, sel []string, more string) ([][]string, error)

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 (*Db) SetFldDef

func (db *Db) SetFldDef(id, str string)

SetFldDef sets id & str field names of TblDef,

if not got automatically.

func (Db) ShrinkIDs

func (db Db) ShrinkIDs(table string, fun func(b4, aft string)) error

ShrinkIDs reorganizes table with compacted IDs Parameters: fun is called before changing one ID with old and new values

func (Db) UpdatePairID

func (db Db) UpdatePairID(table string, idOld, idNew string) error

UpdatePairID updates ID

func (Db) UpdatePairWtParams

func (db Db) UpdatePairWtParams(table string, id, str string) error

UpdatePairWtParams updates value by ID

func (Db) UpdateWtParams

func (db Db) 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 LocationInfo

type LocationInfo struct {
	// there may be more members in this struct,
	// so use member names during instance creation
	Latitude, Longitude float32
	Type                int
	Label, TypeStr      string
}

LocationInfo location info

func (*LocationInfo) Parse

func (loc *LocationInfo) 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 (*LocationInfo) ParseLaLo

func (loc *LocationInfo) ParseLaLo(in interface{}, lalo string) bool

ParseLaLo sets a string or float64 to latitude or longitude

func (*LocationInfo) ParseLevel

func (loc *LocationInfo) ParseLevel(types *CfgMapTypes, 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 (*LocationInfo) SetLabel

func (loc *LocationInfo) SetLabel(lbl any) bool

SetLabel sets label for a location Return value: whether set

func (LocationInfo) String

func (loc LocationInfo) 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

func ReorderParams4Map(pi Pairs[string, string]) (
	po Pairs[string, string], ret string)

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

func (ps *Pairs[K, V]) FindKey(s K) (ret V, err error)

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

func (ps *Pairs[K, V]) FindVal(s V) (ret K, err error)

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

func (ps *Pairs[K, V]) Get(index int) (rK K, rV V, err error)

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

func (ps *Pairs[K, V]) GetNMove() (rK K, rV V, err error)

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]) IsSorted

func (ps Pairs[K, V]) IsSorted() bool

func (Pairs[K, V]) Len

func (ps Pairs[K, V]) Len() int

Len gets size of the collection

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

func (ps *Pairs[K, V]) Set(index int, key K, val V) error

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

func (*Pairs[K, V]) SetPrev

func (ps *Pairs[K, V]) SetPrev(key K, val V) error

SetPrev sets values of previous ellement in the collection,

after calling GetNMove(). cursor not moved

this makes the collection unsorted Return value:

ErrOutOfBound if collection is empty

func (*Pairs[K, V]) Sort

func (ps *Pairs[K, V]) Sort()

Sort sorts the collection by key and Rewind()

type PathInfo

type PathInfo struct {
	// there may be more members in this struct,
	// so use member names during instance creation
	Distance, Duration         float32
	UnitDistance, UnitDuration float32
}

PathInfo info of a path

func (PathInfo) Normalize

func (path PathInfo) Normalize(val, unit float32) (ret float32)

Normalize calculates a value in a unit to a default one

func (*PathInfo) ParseFlt

func (path *PathInfo) ParseFlt(v interface{}) (ret32 float32)

ParseFlt parses a float

func (*PathInfo) ParseUnit

func (path *PathInfo) ParseUnit(types CfgMapTypes, v interface{}) (ret float32)

ParseUnit parses a unit

Jump to

Keyboard shortcuts

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