ss

package module
v0.0.0-...-2d1bf66 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2024 License: MIT Imports: 49 Imported by: 53

README

ss

  1. func If[T any](condition bool, a, b T) T
  2. func IfFunc[T any](condition bool, a, b func() T) T
  3. func ToSet[K comparable](v []K) map[K]bool
  4. func Parse[T Parseable](str string) (T, error)
  5. func IndexN(s, sep string, n int) int
  6. func Must[A any](a A, err error) A
  7. func Or[T comparable](a, b T) T
  8. func FnMatch(pattern, name string, caseInsensitive bool) (matched bool, err error) 文件名模式匹配
  9. Contains, AnyOf, IndexOf, Split, Split2, HasPrefix, HasSuffix
  10. Abbreviate 缩略
  11. QuoteSingle, UnquoteSingle 单引号引用
  12. ss.Base64().Encode/Decode base64 编码/解码
  13. pf, err := rt.StartMemProf() 开始记录 mem profile
  14. pf, err := rt.StartCPUProf() 开始记录 cpu profile
  15. ExpandHome 展开 ~ 主目录
  16. WriteTempFile 写临时文件
  17. Exists 文件是否存在
  18. Close 关闭多个 io.Closer
  19. ReadAll 从 io.Reader 中读取为字符串
  20. ExpandAtFile 扩展 @file 字符串,读取文件内容
  21. ExpandFilename 扩展文件名中的主目录,以及解析符号文件实际实际指向
  22. OpenInBrowser 在默认浏览器中打开链接
  23. SplitToMap 将字符串 s 分割成 map
  24. IsDigits 判断字符串是否全部是数字组成
  25. JoinMap 将 map 中的 key 和 value 拼接成字符串
  26. GetFuncName 获取函数名

中国身份证等随机信息

fmt.Println("姓名:", ss.Rand().ChineseName())
fmt.Println("性别:", ss.Rand().Sex())
fmt.Println("地址:", ss.Rand().Address())
fmt.Println("手机:", ss.Rand().Mobile())
fmt.Println("身份证:", ss.Rand().ChinaID())
fmt.Println("有效期:", ss.Rand().ValidPeriod())
fmt.Println("发证机关:", ss.Rand().IssueOrg())
fmt.Println("邮箱:", ss.Rand().Email())
fmt.Println("银行卡:", ss.Rand().BankNo())
fmt.Println("日期:", ss.Rand().Time())
姓名: 武锴脹
性别: 男
地址: 四川省攀枝花市嫯航路3755号婘螐小区3单元1216室
手机: 18507708621
身份证: 156315197605103397
有效期: 20020716-20220716
发证机关: 平凉市公安局某某分局
邮箱: wvcykkyh@kjsth.co
银行卡: 6230959897028597497
日期: 1977-06-16 23:41:28 +0800 CST

Humane Sizes

This lets you take numbers like 82854982 and convert them to useful strings like, 83 MB or 79 MiB (whichever you prefer).

Example:

fmt.Printf("That file is %s.", ss.Bytes(82854982)) // That file is 83 MB.
Resources
  1. Chinese Id Card Number (Resident Identity Card) and name Generator
  2. China ID

strcase

forked from https://github.com/iancoleman/strcase

strcase is a go package for converting string to various cases (e.g. snake case or camel case) to see the full conversion table below.

Example
s Function Result
AnyKind of string v5 ToSnake(s) any_kind_of_string_v5
AnyKind of string v5 ToSnakeUpper(s) ANY_KIND_OF_STRING_V5
AnyKind of string v5 ToKebab(s) any-kind-of-string-v5
AnyKind of string v5 ToKebabUpper(s) ANY-KIND-OF-STRING5-V5
AnyKind of string v5 ToDelimited(s, '.') any.kind.of.string.v5
AnyKind of string v5 ToDelimitedUpper(s, '.') ANY.KIND.OF.STRING.V5
AnyKind of string v5 ToCamel(s) AnyKindOfStringV5
mySQL ToCamel(s) MySql
AnyKind of string v5 ToCamelLower(s) anyKindOfStringV5
ID ToCamelLower(s) id
SQLMap ToCamelLower(s) sqlMap
TestCase ToCamelLower(s) fooBar
foo-bar ToCamelLower(s) fooBar
foo_bar ToCamelLower(s) fooBar

case conversion types:

  • Camel Case (e.g. CamelCase)
  • Lower Camel Case (e.g. lowerCamelCase)
  • Snake Case (e.g. snake_case)
  • Screaming Snake Case (e.g. SCREAMING_SNAKE_CASE)
  • Kebab Case (e.g. kebab-case)
  • Screaming Kebab Case(e.g. SCREAMING-KEBAB-CASE)
  • Dot Notation Case (e.g. dot.notation.case)
  • Screaming Dot Notation Case (e.g. DOT.NOTATION.CASE)
  • Title Case (e.g. Title Case)
  • Other delimiters
resources
  1. caps a case conversion library for Go

Documentation

Index

Examples

Constants

View Source
const (
	Byte = 1 << (iota * 10)
	KiByte
	MiByte
	GiByte
	TiByte
	PiByte
	EiByte
)

IEC Sizes. kibis of bits

View Source
const (
	IByte = 1
	KByte = IByte * 1000
	MByte = KByte * 1000
	GByte = MByte * 1000
	TByte = GByte * 1000
	PByte = TByte * 1000
	EByte = PByte * 1000
)

SI Sizes.

View Source
const DefaultEllipse = "…"

DefaultEllipse is the default char for marking abbreviation

View Source
const PbePwd = "pbepwd"

PbePwd defines the keyword for client flag.

View Source
const Separator = os.PathSeparator

Variables

View Source
var (
	ErrTagSyntax      = errors.New("bad syntax for struct tag pair")
	ErrTagKeySyntax   = errors.New("bad syntax for struct tag key")
	ErrTagValueSyntax = errors.New("bad syntax for struct tag value")
	ErrKeyNotExist    = errors.New("tag key does not exist")
	ErrTagNotExist    = errors.New("tag does not exist")
)
View Source
var AreaCode = [...]string{
	"11", "12", "13", "14", "15", "21", "22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42", "43", "44",
	"45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64", "65", "71", "81", "82", "91",
}
View Source
var AreaCodeMap = map[string]string{
	"11": "北京", "12": "天津", "13": "河北", "14": "山西", "15": "内蒙古", "21": "辽宁", "22": "吉林", "23": "黑龙江",
	"31": "上海", "32": "江苏", "33": "浙江", "34": "安徽", "35": "福建", "36": "江西", "37": "山东", "41": "河南", "42": "湖北",
	"43": "湖南", "44": "广东", "45": "广西", "46": "海南", "50": "重庆", "51": "四川", "52": "贵州", "53": "云南", "54": "西藏",
	"61": "陕西", "62": "甘肃", "63": "青海", "64": "宁夏", "65": "新疆", "71": "台湾", "81": "香港", "82": "澳门", "91": "国外",
}
View Source
var ErrBadPattern = errors.New("syntax error in pattern")

ErrBadPattern indicates a pattern was malformed.

View Source
var ErrSyntax = errors.New("invalid syntax")
View Source
var Surnames = []string{}/* 292 elements not displayed */
View Source
var ValCodeArr = [...]string{
	"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2",
}
View Source
var Wi = [...]int{
	7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2,
}

Functions

func Abbreviate

func Abbreviate(s string, maxLen int, ellipse string) string

Abbreviate 将 string/[]byte 缩略到 maxLen (不包含 ellipse)

func AbbreviateAny

func AbbreviateAny(s any, maxLen int, ellipse string) any

func AbbreviateBytes

func AbbreviateBytes(p []byte, maxLen int, ellipse string) []byte

func Alphanumeric

func Alphanumeric(u uint8) bool

Alphanumeric tells u is letter or digit char.

func AnyOf

func AnyOf[T comparable](target T, anys ...T) bool

func AnyOfFunc

func AnyOfFunc[T any](target T, f func(idx int, elem, target T) bool, anys ...T) bool

func Base64

func Base64() *b64

func Bytes

func Bytes(s uint64) string

Bytes produces a human readable representation of an SI size.

See also: ParseBytes.

Bytes(82854982) -> 83 MB

func Close

func Close[T io.Closer](closers ...T) error

func CommonDir

func CommonDir(dirs []string) string

CommonDir returns the common directory for a slice of directories.

func Contains

func Contains(s string, subs ...string) bool

func ContainsFold

func ContainsFold(s string, subs ...string) bool

func CopyShuffle

func CopyShuffle[T any](a []T) []T

func DecodeBase64

func DecodeBase64(dst io.Writer, src io.Reader) (int64, error)

Decode copies io.Reader which is in base64 format ( any one of StdEncoding/URLEncoding/RawStdEncoding/RawURLEncoding).

func EncodeBase64

func EncodeBase64(dst io.Writer, src io.Reader, flags ...Base64Flags) (int64, error)

EncodeBase64 copies io.Reader to io.Writer which is in base64 format ( any one of StdEncoding/URLEncoding/RawStdEncoding/RawURLEncoding).

func Eval

func Eval(s string, varValue VarValue) string

func Exists

func Exists(name string) (bool, error)

func Exit

func Exit(msg string, code int)

func ExitIfErr

func ExitIfErr(err error)

func ExpandAtFile

func ExpandAtFile(s string) (string, error)

ExpandAtFile returns argument s if it starts with @filename, the file contents will be replaced as the data.

func ExpandFilename

func ExpandFilename(file string) (string, error)

ExpandFilename first expand ~, then expand symbol link

func ExpandHome

func ExpandHome(s string) string

func ExpandRange

func ExpandRange(f string) []string

ExpandRange expands a string like 1-3 to [1,2,3]

func Fields

func Fields(s string, count int) []string

Fields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of s or an empty slice if s contains only white space. The count determines the number of substrings to return:

n > 0: at most n substrings; the last substring will be the unsplit remainder.
n == 0: the result is nil (zero substrings)
n < 0: all substrings

Code are copy from strings.Fields and add count parameter to control the max fields.

func FieldsFunc

func FieldsFunc(s string, count int, f func(rune) bool) []string

FieldsFunc splits the string s at each run of Unicode code points c satisfying f(c) and returns an array of slices of s. If all code points in s satisfy f(c) or the string is empty, an empty slice is returned. FieldsFunc makes no guarantees about the order in which it calls f(c). If f does not return consistent results for a given c, FieldsFunc may crash.

func FieldsFuncX

func FieldsFuncX(s, keepStart, keepEnd string, count int, f func(rune) bool) []string

FieldsFuncX splits the string s at each run of Unicode code points c satisfying f(c) and returns an array of slices of s. If all code points in s satisfy f(c) or the string is empty, an empty slice is returned. FieldsFunc makes no guarantees about the order in which it calls f(c). If f does not return consistent results for a given c, FieldsFunc may crash.

func FieldsX

func FieldsX(s, keepStart, keepEnd string, count int) []string

FieldsX splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of s or an empty slice if s contains only white space. The count determines the number of substrings to return:

n > 0: at most n substrings; the last substring will be the unsplit remainder.
n == 0: the result is nil (zero substrings)
n < 0: all substrings

Code are copy from strings.Fields and add count parameter to control the max fields.

func FindFlag

func FindFlag(args []string, targetNames ...string) (value string, found bool)

func FnMatch

func FnMatch(pattern, name string, caseInsensitive bool) (matched bool, err error)

FnMatch reports whether name matches the shell file name pattern in case insensitive for non-pattern parts. The pattern syntax is:

pattern:
	{ term }
term:
	'*'         matches any sequence of non-Separator characters
	'?'         matches any single non-Separator character
	'[' [ '^' ] { character-range } ']'
	            character class (must be non-empty)
	c           matches character c (c != '*', '?', '\\', '[')
	'\\' c      matches character c

character-range:
	c           matches character c (c != '\\', '-', ']')
	'\\' c      matches character c
	lo '-' hi   matches character c for lo <= c <= hi

Match requires pattern to match all of name, not just a substring. The only possible returned error is ErrBadPattern, when pattern is malformed.

On Windows, escaping is disabled. Instead, '\\' is treated as path separator.

func GetFuncName

func GetFuncName(i interface{}) string

GetFuncName returns the func name of a func.

func GetPbePwd

func GetPbePwd() string

GetPbePwd read pbe password from viper, or from stdin.

func Getenv

func Getenv[T Parseable](name string, defaultValue T) (T, error)

Getenv 获取环境变量的值

func GetenvBool

func GetenvBool(envName string, defaultValue bool) (bool, error)

func GetenvBytes

func GetenvBytes(name string, defaultValue uint64) (uint64, error)

GetenvBytes 获得环境变量 name 的值所表示的大小,例如. 30MiB

func Gzip

func Gzip(data []byte) ([]byte, error)

func HasPrefix

func HasPrefix(s string, prefix ...string) bool

func HasSuffix

func HasSuffix(s string, suffix ...string) bool

func IBytes

func IBytes(s uint64) string

IBytes produces a human readable representation of an IEC size.

See also: ParseBytes.

IBytes(82854982) -> 79 MiB

func If

func If[T any](condition bool, a, b T) T
Example
package main

import (
	"fmt"

	"github.com/bingoohuang/ngg/ss"
)

func main() {
	fmt.Println(ss.If(true, "bingoo", "huang"))
	fmt.Println(ss.If(false, "bingoo", "huang"))
}
Output:

bingoo
huang

func IfFunc

func IfFunc[T any](condition bool, a, b func() T) T

func IndexN

func IndexN(s, sep string, n int) int

IndexN 返回字符串 s 中第 n 个子字符串 sub 的索引。 如果 n 是正数,则从左到右查找第 n 个 sub 的位置。 如果 n 是负数,则从右到左查找第 -n 个 sub 的位置。 如果找不到,返回 -1

func IndexOf

func IndexOf[T comparable](target T, anys ...T) int

func IndexOfFunc

func IndexOfFunc[T any](target T, f func(idx int, elem, target T) bool, anys ...T) int

func Is029

func Is029(v int32) bool

Is029 tells v is 0-9

func IsA2Z

func IsA2Z(v int32) bool

IsA2Z tells v is A-Z

func IsDigits

func IsDigits(s string) bool

func Isa2z

func Isa2z(v int32) bool

Isa2z tells v is a-z

func JSONPretty

func JSONPretty(data any) string

JSONPretty prettify the JSON encoding of data

func Json

func Json(v any) []byte

func Lines

func Lines(filePath string) (lines []string, err error)

Lines read file into lines.

func LinesChan

func LinesChan(filePath string, chSize int) (ch chan string, err error)

LinesChan read file into lines.

func MapGet

func MapGet[K comparable, V any](m map[K]V, k K, defaultVal V) V

func MapGetF

func MapGetF[K comparable, V any](m map[K]V, k K, defaultF func() V) V

func MapJoin

func MapJoin[K comparable, V any](m map[K]V, kkSep, kvSep string) string

func MapKeys

func MapKeys[K comparable, V any](m map[K]V) []K

func MapKeysSorted

func MapKeysSorted[K constraints.Ordered, V any](m map[K]V) []K

func MapValues

func MapValues[K comparable, V any](m map[K]V) []V

func MapWalk

func MapWalk[K comparable, V any](m map[K]V, walker func(k K, v V) bool)

func Must

func Must[A any](a A, err error) A

func OpenInBrowser

func OpenInBrowser(addr string, paths ...string) (string, error)

func Or

func Or[T comparable](a, b T) T

func PanicErr

func PanicErr(err error)

func Parse

func Parse[T Parseable](str string) (T, error)

func ParseArgs

func ParseArgs(a interface{}, args []string, optionFns ...FlagParseOptionsFn)

func ParseBool

func ParseBool(s string) (bool, error)

ParseBool returns the boolean value represented by the string. It accepts 1, t, true, y, yes, on as true with camel case incentive and accepts 0, f false, n, no, off as false with camel case incentive Any other value returns an error.

func ParseBytes

func ParseBytes(s string) (uint64, error)

ParseBytes parses a string representation of bytes into the number of bytes it represents.

See Also: Bytes, IBytes.

ParseBytes("42 MB") -> 42000000, nil ParseBytes("42 mib") -> 44040192, nil

func ParseDuration

func ParseDuration(s string) time.Duration

func ParseFlag

func ParseFlag(a interface{}, optionFns ...FlagParseOptionsFn)

func PbeDecode

func PbeDecode(p string) (string, error)

PbeDecode decrypts p by PBEWithMD5AndDES with 19 iterations.

func PbeDecrypt

func PbeDecrypt(cipherText, password string, iterations int) (string, error)

PbeDecrypt PrintDecrypt the cipherText(result of Encrypt) based on password and iterations.

func PbeDecryptFile

func PbeDecryptFile(filename, passStr string)

func PbeDecryptSalt

func PbeDecryptSalt(cipherText, password, fixedSalt string, iterations int) (string, error)

PbeDecryptSalt PrintDecrypt the cipherText(result of EncryptSalt) based on password and iterations.

func PbeEncode

func PbeEncode(p string) (string, error)

PbeEncode encrypts p by PBEWithMD5AndDES with 19 iterations. it will prompt password if viper get none.

func PbeEncrypt

func PbeEncrypt(plainText, password string, iterations int) (string, error)

PbeEncrypt PrintEncrypt the plainText based on password and iterations with random salt. The result contains the first 8 bytes salt before BASE64.

func PbeEncryptFile

func PbeEncryptFile(filename, passStr string)

func PbeEncryptFileUpdate

func PbeEncryptFileUpdate(filename, passStr, pbenew string)

func PbeEncryptSalt

func PbeEncryptSalt(plainText, password, fixedSalt string, iterations int) (string, error)

PbeEncryptSalt PrintEncrypt the plainText based on password and iterations with fixed salt.

func PbePrintDecrypt

func PbePrintDecrypt(passStr string, cipherText ...string)

PbePrintDecrypt prints the PBE decryption.

func PbePrintEncrypt

func PbePrintEncrypt(passStr string, plains ...string)

PbePrintEncrypt prints the PBE encryption.

func Pick1

func Pick1[T any](a T, _ error) T

func Ptr

func Ptr[T any](val T) *T

func QuoteSingle

func QuoteSingle(s string) string

QuoteSingle returns a single-quoted Go string literal representing s. But, nothing else escapes.

Example
package main

import (
	"fmt"

	"github.com/bingoohuang/ngg/ss"
)

func main() {
	s := ss.QuoteSingle(`"Fran & Freddie's Diner	☺"`)
	fmt.Println(s)
	s = ss.QuoteSingle(`rock'n'roll`)
	fmt.Println(s)
}
Output:

'"Fran & Freddie\'s Diner	☺"'
'rock\'n\'roll'

func Rand

func Rand() random

func ReadAll

func ReadAll(r io.Reader) (string, error)

func ReadFile

func ReadFile(filename string) ([]byte, error)

ReadFile reads a file content, if it's a .gz, decompress it.

func Repeat

func Repeat(s, separator string, count int) string

Repeat returns a new string consisting of count copies of the string s with separator.

It panics if count is negative or if the result of (len(s) * count) overflows.

func ScanLines

func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error)

ScanLines is a split function for a Scanner that returns each line of text, with end-of-line marker. The returned line may be empty. The end-of-line marker is one optional carriage return followed by one mandatory newline. In regular expression notation, it is `\r?\n`. The last non-empty line of input will be returned even if it has no newline.

func Split

func Split(s, sep string) []string
Example
for _, c := range []string{
	"",
	"lowercase",
	"Class",
	"MyClass",
	"MyC",
	"HTML",
	"PDFLoader",
	"AString",
	"SimpleXMLParser",
	"vimRPCPlugin",
	"GL11Version",
	"99Bottles",
	"May5",
	"BFG9000",
	"BöseÜberraschung",
	"Two  spaces",
	"BadUTF8\xe2\xe2\xa1",
} {
	fmt.Printf("%#v => %#v\n", c, SplitCamelcase(c).Entries())
}
Output:

"" => []string{}
"lowercase" => []string{"lowercase"}
"Class" => []string{"Class"}
"MyClass" => []string{"My", "Class"}
"MyC" => []string{"My", "C"}
"HTML" => []string{"HTML"}
"PDFLoader" => []string{"PDF", "Loader"}
"AString" => []string{"A", "String"}
"SimpleXMLParser" => []string{"Simple", "XML", "Parser"}
"vimRPCPlugin" => []string{"vim", "RPC", "Plugin"}
"GL11Version" => []string{"GL", "11", "Version"}
"99Bottles" => []string{"99", "Bottles"}
"May5" => []string{"May", "5"}
"BFG9000" => []string{"BFG", "9000"}
"BöseÜberraschung" => []string{"Böse", "Überraschung"}
"Two  spaces" => []string{"Two", "  ", "spaces"}
"BadUTF8\xe2\xe2\xa1" => []string{"BadUTF8\xe2\xe2\xa1"}

func Split2

func Split2(s, sep string) (s1, s2 string)

func SplitFunc

func SplitFunc(idx int, sub, subSep string, cur []string) (splitSub string, ok, kontinue bool)

func SplitN

func SplitN(s, sep string, n int, f func(idx int, sub, subSep string, cur []string) (splitSub string, ok, kontinue bool)) []string

func SplitReg

func SplitReg(s string, re *regexp.Regexp, n int) []string

SplitReg slices s into substrings separated by the expression and returns a slice of the substrings between those expression matches. (especially including the tail separator.)

The slice returned by this method consists of all the substrings of s not contained in the slice returned by FindAllString. When called on an expression that contains no metacharacters, it is equivalent to strings.SplitN.

Example:

s := regexp.MustCompile("a*").SplitReg("abaabaccadaaae", 5)
// s: ["", "b", "b", "c", "cadaaae"]

The count determines the number of substrings to return:

n > 0: at most n substrings; the last substring will be the unsplit remainder.
n == 0: the result is nil (zero substrings)
n < 0: all substrings

func SplitSeps

func SplitSeps(s string, seps string, n int) []string

func SplitToMap

func SplitToMap(s string, kkSep, kvSep string) map[string]string

SplitToMap 将字符串 s 分割成 map, 其中 key 和 value 之间的间隔符是 kvSep, kv 和 kv 之间的分隔符是 kkSep

func SplitX

func SplitX(s string, separate string, ocs ...OpenClose) []string

SplitX splits s by separate (not in (),[],{})

func ToCamel

func ToCamel(s string) string

ToCamel converts a string to CamelCase

func ToCamelLower

func ToCamelLower(s string) string

ToCamelLower converts a string to lowerCamelCase

func ToDelimited

func ToDelimited(s string, del uint8) string

ToDelimited converts a string to delimited.snake.case (in this case `del = '.'`)

func ToDelimitedScreaming

func ToDelimitedScreaming(s string, del uint8, screaming bool) string

ToDelimitedScreaming converts a string to SCREAMING.DELIMITED.SNAKE.CASE (in this case `del = '.'; screaming = true`) or delimited.snake.case (in this case `del = '.'; screaming = false`)

func ToDelimitedUpper

func ToDelimitedUpper(s string, del uint8) string

ToDelimitedUpper converts a string to SCREAMING.DELIMITED.SNAKE.CASE (in this case `del = '.'; screaming = true`) or delimited.snake.case (in this case `del = '.'; screaming = false`)

func ToKebab

func ToKebab(s string) string

ToKebab converts a string to kebab-case

func ToKebabUpper

func ToKebabUpper(s string) string

ToKebabUpper converts a string to SCREAMING-KEBAB-CASE

func ToSet

func ToSet[K comparable](v []K) map[K]bool

func ToSnake

func ToSnake(s string) string

ToSnake converts a string to snake_case

func ToSnakeUpper

func ToSnakeUpper(s string) string

ToSnakeUpper converts a string to SCREAMING_SNAKE_CASE

func Ungzip

func Ungzip(data []byte) ([]byte, error)

func UnquoteSingle

func UnquoteSingle(s string) (string, error)

UnquoteSingle interprets s as a single-quoted Go string literal, returning the string value that s quotes.

Example
package main

import (
	"fmt"

	"github.com/bingoohuang/ngg/ss"
)

func main() {
	s, err := ss.UnquoteSingle("You can't unquote a string without quotes")
	fmt.Printf("%q, %v\n", s, err)
	s, err = ss.UnquoteSingle("\"The string must be either double-quoted\"")
	fmt.Printf("%q, %v\n", s, err)
	s, err = ss.UnquoteSingle("`or backquoted.`")
	fmt.Printf("%q, %v\n", s, err)
	s, err = ss.UnquoteSingle("'\u263a'")
	fmt.Printf("%q, %v\n", s, err)
	s, err = ss.UnquoteSingle("'\u2639\u2639'")
	fmt.Printf("%q, %v\n", s, err)
	s, err = ss.UnquoteSingle("'\\'The string must be either single-quoted\\''")
	fmt.Printf("%q, %v\n", s, err)
}
Output:

"", invalid syntax
"", invalid syntax
"", invalid syntax
"☺", <nil>
"☹☹", <nil>
"'The string must be either single-quoted'", <nil>

func WriteTempFile

func WriteTempFile(tempDir, pattern string, data []byte, errorPanic bool) (name string, err error)

WriteTempFile writes the content to a temporary file.

Types

type Base64Flags

type Base64Flags uint8
const (
	Std Base64Flags = 1 << iota
	Url
	Raw
)

type CamelCaseEntries

type CamelCaseEntries []CamelCaseEntry

func SplitCamelcase

func SplitCamelcase(src string) (entries CamelCaseEntries)

SplitCamelcase splits the camelcase word and returns a list of words. It also supports digits. Both lower camel case and upper camel case are supported. For more info please check: http://en.wikipedia.org/wiki/CamelCase https://github.com/proproto/camelcase/blob/master/camelcase.go

Examples

"" =>                     [""]
"lowercase" =>            ["lowercase"]
"Class" =>                ["Class"]
"MyClass" =>              ["My", "Class"]
"MyC" =>                  ["My", "C"]
"HTML" =>                 ["HTML"]
"PDFLoader" =>            ["PDF", "Loader"]
"AString" =>              ["A", "String"]
"SimpleXMLParser" =>      ["Simple", "XML", "Parser"]
"vimRPCPlugin" =>         ["vim", "RPC", "Plugin"]
"GL11Version" =>          ["GL", "11", "Version"]
"99Bottles" =>            ["99", "Bottles"]
"May5" =>                 ["May", "5"]
"BFG9000" =>              ["BFG", "9000"]
"BöseÜberraschung" =>     ["Böse", "Überraschung"]
"Two  spaces" =>          ["Two", "  ", "spaces"]
"BadUTF8\xe2\xe2\xa1" =>  ["BadUTF8\xe2\xe2\xa1"]

Splitting rules

  1. If string is not valid UTF-8, return it without splitting as single item array.
  2. Assign all unicode characters into one of 4 sets: lower case letters, upper case letters, numbers, and all other characters.
  3. Iterate through characters of string, introducing splits between adjacent characters that belong to different sets.
  4. Iterate through array of split strings, and if a given string is upper case: if subsequent string is lower case: move last character of upper case string to beginning of lower case string

func (CamelCaseEntries) Entries

func (c CamelCaseEntries) Entries() []string

type CamelCaseEntry

type CamelCaseEntry struct {
	Class CamelCaseEntryClass
	Entry string
}

func (CamelCaseEntry) String

func (c CamelCaseEntry) String() string

type CamelCaseEntryClass

type CamelCaseEntryClass int
const (
	CamelCaseEntryLower CamelCaseEntryClass
	CamelCaseEntryUpper
	CamelCaseEntryDigit
	CamelCaseEntryOther
)

type CardBin

type CardBin struct {
	Name     string
	Length   int
	CardType string
	Prefixes []int
}

type DurFraction

type DurFraction struct {
	Unit  string
	Value int64
}

func ParseDur

func ParseDur(s string, allowUnits ...string) (time.Duration, []DurFraction, error)

ParseDur parses a duration string(add d and w to standard time.Parse). A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h", "d", "w". allowUnits 允许的单位, 不传,使用上面的 unitMap 中的默认单位

type Expand

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

Expand structured a expandable unit.

func MakeExpand

func MakeExpand(s string) Expand

MakeExpand makes an expand by s.

func (Expand) MakeExpand

func (f Expand) MakeExpand() []string

MakeExpand makes a expanded string slice of expand.

func (Expand) MakePart

func (f Expand) MakePart() ExpandPart

MakePart makes a part of expand.

func (Expand) MaxLen

func (f Expand) MaxLen() int

MaxLen returns the max length among the inner parts.

type ExpandPart

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

ExpandPart as a part of something.

func MakeExpandPart

func MakeExpandPart(s string) ExpandPart

MakeExpandPart makes an expanded part.

func MakeFixedPart

func MakeFixedPart(s string) ExpandPart

MakeFixedPart make a fixed part by s.

func MakePart

func MakePart(s []string) ExpandPart

MakePart make a direct part by s.

func (ExpandPart) ExpandPart

func (f ExpandPart) ExpandPart(i int) string

ExpandPart returns i'th item.

func (ExpandPart) Len

func (f ExpandPart) Len() int

Len returns the length of part items.

type Expandable

type Expandable interface {
	// MakePart returns i'th item.
	ExpandPart(i int) string
	// Len returns the length of part items.
	Len() int
}

Expandable abstract a thing that can be expanded to parts.

type FlagParseOptions

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

type FlagParseOptionsFn

type FlagParseOptionsFn func(*FlagParseOptions)

func AutoLoadYaml

func AutoLoadYaml(flagName, defaultCnf string) FlagParseOptionsFn

type FlagPostProcessor

type FlagPostProcessor interface {
	PostProcess()
}

type FlagSize

type FlagSize uint64

func (*FlagSize) Set

func (i *FlagSize) Set(value string) error

func (*FlagSize) String

func (i *FlagSize) String() string

func (*FlagSize) Type

func (i *FlagSize) Type() string

type FlagStringBool

type FlagStringBool struct {
	Val    string
	Exists bool
}

func (*FlagStringBool) Get

func (i *FlagStringBool) Get() interface{}

func (*FlagStringBool) Set

func (i *FlagStringBool) Set(value string) error

func (*FlagStringBool) SetExists

func (i *FlagStringBool) SetExists(b bool)

func (*FlagStringBool) String

func (i *FlagStringBool) String() string

func (*FlagStringBool) Type

func (i *FlagStringBool) Type() string

type FlagUsageShower

type FlagUsageShower interface {
	Usage() string
}

type FlagVersionShower

type FlagVersionShower interface {
	VersionInfo() string
}

type GenFn

type GenFn func() any

type GenFnFn

type GenFnFn func(params string) GenFn

type Literal

type Literal struct{ V string }

func (Literal) Eval

func (l Literal) Eval(VarValue) string

type MapGenValue

type MapGenValue struct {
	Map map[string]GenFn
	sync.RWMutex

	GenMap     map[string]GenFnFn
	MissedVars map[string]bool
	Vars       map[string]any
}

func NewMapGenValue

func NewMapGenValue(m map[string]GenFnFn) *MapGenValue

func (*MapGenValue) GetValue

func (m *MapGenValue) GetValue(name, params, expr string) any

func (*MapGenValue) Value

func (m *MapGenValue) Value(name, params, expr string) any

type OpenClose

type OpenClose struct {
	Open  string
	Close string
}

OpenClose stands for open-close strings like ()[]{} and etc.

func (OpenClose) IsSame

func (o OpenClose) IsSame() bool

IsSame tells the open and close is same of not.

type Pair

type Pair[T1 any, T2 any] struct {
	V1 T1
	V2 T2
}

type Parseable

type Parseable interface {
	~bool | ~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
		~float32 | ~float64 | ~complex64 | ~complex128
}

type Part

type Part interface {
	Eval(varValue VarValue) string
}

type Parts

type Parts []Part

func ParseSubstitute

func ParseSubstitute(s string) (parts Parts)

func (Parts) Eval

func (l Parts) Eval(varValue VarValue) string

type Pbe

type Pbe struct {
	Passphrase string
}

Pbe configs the passphrase.

func (Pbe) Change

func (c Pbe) Change(s, newPassphrase string) (string, error)

ChangePbe changes the {PBE}xxx to {PBE} yyy with a new passphase

func (Pbe) Decode

func (c Pbe) Decode(s string) (string, error)

Decode free the {PBE}xxx to yyy with a passphrase

func (Pbe) Decrypt

func (c Pbe) Decrypt(p string) (string, error)

Decrypt decrypts p by PBEWithMD5AndDES with 19 iterations.

func (Pbe) Encode

func (c Pbe) Encode(s string) (string, error)

Encode will PBE encrypt the passwords in the text passwords should be as any of following format and its converted pattern 1. {PWD:clear} -> {PBE:cyphered} 2. [PWD:clear] -> {PBE:cyphered} 3. (PWD:clear) -> {PBE:cyphered} 4. "PWD:clear" -> "{PBE:cyphered}" 5. PWD:clear -> {PBE:cyphered}

func (Pbe) Encrypt

func (c Pbe) Encrypt(p string) (string, error)

Encrypt encrypts p by PBEWithMD5AndDES with 19 iterations. it will prompt password if viper get none.

type Prof

type Prof interface {
	io.Closer
}
var NoopProfile Prof = &noopProfile{}

func StartCPUProf

func StartCPUProf(name string) (Prof, error)

StartCPUProf 创建 CPU 性能分析文件

func StartMemProf

func StartMemProf(name string) (Prof, error)

StartMemProf 创建内存性能分析文件

type RandImgConfig

type RandImgConfig struct {
	Width      int
	Height     int
	RandomText string
	FastMode   bool
	PixelSize  int
}

func (*RandImgConfig) Gen

func (c *RandImgConfig) Gen(imageFormat string) ([]byte, int)

Gen generate a random image with imageFormat (jpg/png) . refer: https://onlinejpgtools.com/generate-random-jpg

func (*RandImgConfig) GenFile

func (c *RandImgConfig) GenFile(filename string, fileSize int) int

type RandomImageResult

type RandomImageResult struct {
	Size     int
	Filename string
}

type StructTag

type StructTag struct {
	// Key is the tag key, such as json, xml, etc..
	// i.e: `json:"foo,omitempty". Here key is: "json"
	Key string

	// Name is a part of the value
	// i.e: `json:"foo,omitempty". Here name is: "foo"
	Name string

	// Options is a part of the value. It contains a slice of tag options i.e:
	// `json:"foo,omitempty". Here options is: ["omitempty"]
	Options []string

	// OptionsMap is a map of the options
	// i.e: `json:"foo,omitempty". Here OptionsMap is: {"foo":"", "omitempty": ""}
	OptionsMap map[string]string

	// Raw is the raw value of the tag
	// i.e: `json:"foo,omitempty". Here Raw is: "foo,omitempty"
	Raw string
}

StructTag defines a single struct's string literal tag

func ParseStructTag

func ParseStructTag(key, value string) *StructTag

func (*StructTag) GetOpt

func (t *StructTag) GetOpt(optName string) string

GetOpt gets opt's value by its name

func (*StructTag) GoString

func (t *StructTag) GoString() string

GoString implements the fmt.GoStringer interface

func (*StructTag) HasOption

func (t *StructTag) HasOption(opt string) bool

HasOption returns true if the given option is available in options

func (*StructTag) String

func (t *StructTag) String() string

String reassembles the tag into a valid tag field representation

func (*StructTag) Value

func (t *StructTag) Value() string

Value returns the raw value of the tag, i.e. if the tag is `json:"foo,omitempty", the Value is "foo,omitempty"

type StructTags

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

StructTags represent a set of tags from a single struct field

func ParseStructTags

func ParseStructTags(tag string) (*StructTags, error)

Parse parses a single struct field tag and returns the set of tags.

func (*StructTags) AddOptions

func (t *StructTags) AddOptions(key string, options ...string) error

AddOptions adds the given option for the given key. If the option already exists it doesn't add it again.

func (*StructTags) Delete

func (t *StructTags) Delete(keys ...string)

Delete deletes the tag for the given keys

func (*StructTags) DeleteOptions

func (t *StructTags) DeleteOptions(key string, options ...string) error

DeleteOptions deletes the given options for the given key

func (*StructTags) Get

func (t *StructTags) Get(key string) (*StructTag, error)

Get returns the tag associated with the given key. If the key is present in the tag the value (which may be empty) is returned. Otherwise, the returned value will be the empty string. The ok return value reports whether the tag exists or not (which the return value is nil).

func (*StructTags) GetTag

func (t *StructTags) GetTag(key string) string

func (*StructTags) Keys

func (t *StructTags) Keys() []string

Keys returns a slice of tags' keys.

func (*StructTags) Len

func (t *StructTags) Len() int

func (*StructTags) Less

func (t *StructTags) Less(i int, j int) bool

func (*StructTags) Set

func (t *StructTags) Set(tag *StructTag) error

Set sets the given tag. If the tag key already exists it'll override it

func (*StructTags) String

func (t *StructTags) String() string

String reassembles the tags into a valid literal tag field representation

func (*StructTags) Swap

func (t *StructTags) Swap(i int, j int)

func (*StructTags) Tags

func (t *StructTags) Tags() []*StructTag

Tags returns a slice of tags. The order is the original tag order unless it was changed.

type Sub

type Sub interface {
	IsVar() bool
}

type SubTxt

type SubTxt struct {
	Val string
}

func (SubTxt) IsVar

func (s SubTxt) IsVar() bool

type SubVar

type SubVar struct {
	Name   string
	Params string
	Expr   string
}

func (SubVar) IsVar

func (s SubVar) IsVar() bool

type Subs

type Subs []Sub

func ParseExpr

func ParseExpr(src string) Subs

func (Subs) CountVars

func (s Subs) CountVars() (count int)

func (Subs) Eval

func (s Subs) Eval(valuer Valuer) (any, error)

type Valuer

type Valuer interface {
	Value(name, params, expr string) (any, error)
}

type ValuerHandler

type ValuerHandler func(name, params string) (any, error)

func (ValuerHandler) Value

func (f ValuerHandler) Value(name, params string) (any, error)

type Var

type Var struct {
	Name string
	Expr string
}

func (Var) Eval

func (l Var) Eval(varValue VarValue) string

type VarValue

type VarValue interface {
	GetValue(name, params, expr string) any
}

type VarValueHandler

type VarValueHandler func(name, params, expr string) any

func (VarValueHandler) GetValue

func (v VarValueHandler) GetValue(name, params, expr string) any

Jump to

Keyboard shortcuts

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