helper

package
v0.6.4 Latest Latest
Warning

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

Go to latest
Published: Jun 12, 2024 License: GPL-3.0 Imports: 36 Imported by: 0

Documentation

Overview

Package helpers are general, shared functions.

Index

Constants

View Source
const (
	// Eraseline is an ANSI escape control to erase the active line of the terminal.
	Eraseline = "\x1b[2K"
	// Timeout is the HTTP client timeout.
	Timeout = 5 * time.Second
	// ReadWrite is the file mode for read and write access.
	ReadWrite = 0o666
	// User-Agent to send with the HTTP request.
	UserAgent = "Defacto2 2024 app under construction (thanks!)"
)
View Source
const (
	// WriteWriteRead is the file mode for read and write access.
	// The file owner and group has read and write access, and others have read access.
	WriteWriteRead fs.FileMode = 0o664
	// TODO: user and group chown of file?
	DSStore = ".DS_Store" // DSStore is the macOS directory service store file.
)

Variables

View Source
var (
	ErrDiffLength = errors.New("files are of different lengths")
	ErrDirPath    = errors.New("directory path is a file")
	ErrExistPath  = errors.New("path ready exists and will not overwrite")
	ErrFileMatch  = errors.New("helper filematch")
	ErrFilePath   = errors.New("file path is a directory")
	ErrKey        = errors.New("could not generate a random session key")
	ErrOSFile     = errors.New("os file is nil")
	ErrRead       = errors.New("could not read files")
)

Functions

func Add1

func Add1(a any) int64

Add1 returns the value of a + 1. The type of a must be an integer type or the result is 0.

func ByteCount

func ByteCount(b int64) string

ByteCount formats b as in a compact, human-readable unit of measure.

func ByteCountFloat

func ByteCountFloat(b int64) string

ByteCountFloat formats b as in a human-readable unit of measure. Units measured in gigabytes or larger are returned with 1 decimal place.

func CFToUUID

func CFToUUID(cfid string) (string, error)

CFToUUID formats a 35 character, Coldfusion Universally Unique Identifier to a standard, 36 character, Universally Unique Identifier.

func Capitalize

func Capitalize(s string) string

Capitalize returns a string with the first letter of the first word capitalized. If the first word is an acronym, it is capitalized as a word.

func CookieStore

func CookieStore(envKey string) ([]byte, error)

CookieStore generates a key for use with the sessions cookie store middleware. envKey is the value of an imported environment session key. But if it is empty, a 32-bit randomized value is generated that changes on every restart.

The effect of using a randomized key will invalidate all existing sessions on every restart.

func Count

func Count(dir string) (int, error)

Count returns the number of files in the given directory.

func Day

func Day(i int) bool

Day returns true if the i value can be used as a day time value.

func DeObfuscate

func DeObfuscate(s string) string

Deobfuscate the obfuscated string, or return the original string.

func DeleteDupe

func DeleteDupe(s ...string) []string

DeleteDupe removes duplicate strings from a slice. The returned slice is sorted and compacted.

func DeobfuscateID

func DeobfuscateID(id string) int

DeobfuscateID an obfuscated ID to return the primary key of the record. Returns a 0 if the id is not valid.

func DeobfuscateURL

func DeobfuscateURL(rawURL string) int

Deobfuscate an obfuscated record URL to return a record's primary key. A URL can point to a Defacto2 record download or detail page. Returns a 0 if the URL is not valid.

func Determine

func Determine(reader io.Reader) encoding.Encoding

Determine returns the encoding of the plain text byte slice. If the byte slice contains Unicode multi-byte characters then nil is returned. Otherwise a charmap.ISO8859_1 or charmap.CodePage437 encoding is returned.

func Duplicate

func Duplicate(oldpath, newpath string) (int64, error)

Duplicate is a workaround for renaming files across different devices. A cross device can also be a different file system such as a Docker volume.

func File

func File(name string) bool

File returns true if the named file exists on the system.

func FileMatch

func FileMatch(name1, name2 string) (bool, error)

FileMatch returns true if the two named files are the same. It returns false if the files are of different lengths or if an error occurs while reading the files. The read buffer size is 4096 bytes.

func Files

func Files(dir string) ([]string, error)

Files returns the filenames in the given directory.

func Finds

func Finds(name string, names ...string) bool

Finds returns true if the name is found in the collection of names.

func FixSceneOrg

func FixSceneOrg(rawURL string) string

FixSceneOrg returns a working URL if the provided rawURL is a known, broken link to a scene.org file. Otherwise it returns the original URL.

func FmtSlice

func FmtSlice(s string) string

FmtSlice formats a comma separated string.

func GetStat

func GetStat(url string) (int64, error)

GetStat returns the content length of a remote URL. It returns an error if the URL is invalid or the request fails. The content length is -1 if it is unknown.

func Integrity

func Integrity(name string, fs embed.FS) (string, error)

Integrity returns the sha384 hash of the named embed file. This is intended to be used for Subresource Integrity (SRI) verification with integrity attributes in HTML script and link tags.

func IntegrityBytes

func IntegrityBytes(b []byte) string

IntegrityBytes returns the sha384 hash of the given byte slice.

func IntegrityFile

func IntegrityFile(name string) (string, error)

IntegrityFile returns the sha384 hash of the named file. This can be used as a link cache buster.

func LastChr

func LastChr(s string) string

LastChr returns the last character or rune of the string.

func Latency

func Latency() *time.Time

Latency returns the stored, current local time.

func Lines

func Lines(name string) (int, error)

Lines returns the number of lines in the named file.

func LocalHosts

func LocalHosts() ([]string, error)

LocalHosts returns a list of local hostnames.

func LocalIPs

func LocalIPs() ([]net.IP, error)

LocalIPs returns a list of local IP addresses. credit: https://gosamples.dev/local-ip-address/

func MaxLineLength

func MaxLineLength(s string) int

MaxLineLength counts the character length of the longest line in a string.

func Obfuscate

func Obfuscate(s string) string

Obfuscate a numeric string to insecurely hide database primary key values when passed along a URL. This function is a port of a CFWheels framework function programmed in ColdFusion (CFML). https://github.com/cfwheels/cfwheels/blob/cf8e6da4b9a216b642862e7205345dd5fca34b54/wheels/global/misc.cfm#L483

func ObfuscateID

func ObfuscateID(key int64) string

ObfuscateID the primary key of a record as a string that is used as a URL param or path.

func PageCount

func PageCount(sum, limit int) uint

PageCount returns the maximum pages possible for the sum of records with a record limit per-page.

func RenameCrossDevice

func RenameCrossDevice(oldpath, newpath string) error

RenameCrossDevice is a workaround for renaming files across different devices. A cross device can also be a different file system such as a Docker volume.

func RenameFile

func RenameFile(oldpath, newpath string) error

RenameFile renames a file from oldpath to newpath. It returns an error if the oldpath does not exist or is a directory, newpath already exists, or the rename fails.

func RenameFileOW

func RenameFileOW(oldpath, newpath string) error

RenameFileOW renames a file from oldpath to newpath. It returns an error if the oldpath does not exist or is a directory or the rename fails.

func ReverseInt

func ReverseInt(i int) (int, error)

ReverseInt reverses an integer.

func SearchTerm

func SearchTerm(input string) []string

SearchTerm returns a list of search terms from the input string. The input string is split by commas.

func ShortMonth

func ShortMonth(month int) string

ShortMonth takes a month integer and abbreviates it to a three letter English month.

func Size

func Size(name string) int64

Size returns the size of the named file. If the file does not exist, it returns -1.

func Slug

func Slug(name string) string

Slug returns a URL friendly string of the named group.

func SplitAsSpaces

func SplitAsSpaces(s string) string

SplitAsSpaces splits a string at each capital letter.

func Stat

func Stat(name string) bool

Stat stats the named file or directory to confirm it exists on the system.

func StrongIntegrity

func StrongIntegrity(name string) (string, error)

StrongIntegrity returns the SHA-386 checksum value of the named file.

func Sum386

func Sum386(f *os.File) (string, error)

Sum386 returns the SHA-386 checksum value of the open file.

func TimeDistance

func TimeDistance(from, to time.Time, seconds bool) string

TimeDistance describes the difference between two time values. The seconds parameter determines if the string should include seconds.

func Titleize

func Titleize(s string) string

Titleize returns a string with the first letter each word capitalized. If a word is an acronym, it is capitalized as a word.

func Touch

func Touch(name string) error

Touch creates a new, empty named file. If the file already exists, an error is returned.

func TouchW

func TouchW(name string, data ...byte) (int, error)

TouchW creates a new named file with the given data. If the file already exists, an error is returned.

func TrimPunct

func TrimPunct(s string) string

TrimPunct removes any trailing, common punctuation characters from the string.

func TrimRoundBraket

func TrimRoundBraket(s string) string

TrimRoundBraket removes the tailing round brakets and any whitespace.

func TruncFilename

func TruncFilename(w int, name string) string

TruncFilename reduces a filename to the length of w characters. The file extension is always preserved with the truncation.

func Year

func Year(i int) bool

Year returns true if the i value is greater than 1969 or equal to the current year.

func Years

func Years(a, b int16) string

Years returns a string of the years if they are different. If they are the same, it returns a singular year.

Types

type DownloadResponse

type DownloadResponse struct {
	ContentLength string // ContentLength is the size of the file in bytes.
	ContentType   string // ContentType is the MIME type of the file.
	LastModified  string // LastModified is the last modified date of the file.
	Path          string // Path is the path to the downloaded file.
}

DownloadResponse contains the details of a downloaded file.

func GetFile

func GetFile(url string) (DownloadResponse, error)

GetFile downloads a file from a remote URL and saves it to the default temp directory. It returns the path to the downloaded file.

Jump to

Keyboard shortcuts

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