Documentation
¶
Overview ¶
Package my provides a collection of utility functions for Go applications.
This package includes various utility functions organized into several categories:
String Utilities:
- IsEmpty: Checks if a string is empty
- Left, Right, Mid: Extract substrings from different positions
- Len: Count Unicode code points in a string
- Space: Generate a string of spaces
Type Conversion:
- CStr: Convert various types to string
- CInt: Convert string to integer
- CDate: Parse string to time.Time
- BytesToString, StringToBytes: Convert between []byte and string
Date and Time:
- Now: Get current time as formatted string
- FormatDateTime: Format time.Time according to specified pattern
- FriendlyTime: Get human-friendly time elapsed description
Cryptography:
- MD5, SHA1, SHA256: Calculate hash values
- HMACSHA1, HMACSHA256: Generate keyed hash values
File Operations:
- AppPath: Get application path
- FolderExist, FileExist: Check existence of folders and files
- MakeDir: Create directory
- ReadText, WriteText, AppendText: Read and write text files
Network Operations:
- GetURL, PostURL: Make HTTP requests
- GetJSON, PostJSON: Handle JSON data over HTTP
- DownloadFile: Download file from URL
- RecoverWrap: HTTP handler with panic recovery
- RemoteIP, ClientIP: Get client IP addresses
Configuration:
- LoadJSONConfig, LoadXMLConfig: Load configuration from files
- MustLoadConfig: Load configuration or panic
Random Generation:
- RndNumber, RndAlpha, RndString: Generate random strings
- RndFilename: Generate random filenames
Regular Expression:
- Test: Validate strings against common patterns
The package aims to simplify common programming tasks by providing ready-to-use functions that handle frequent operations in Go applications.
Index ¶
- Variables
- func AppPath() string
- func AppendText(filepath string, text string) (err error)
- func BytesToString(b []byte) string
- func CDate(s string) time.Time
- func CInt(s string) int
- func CStr(i int) string
- func ClientIP(r *http.Request) string
- func DownloadFile(url, filepath string) (err error)
- func FileExist(path string) bool
- func FolderExist(path string) bool
- func FormatDateTime(t time.Time, mode dateTimeFormat) string
- func FriendlyTime(t time.Time) string
- func GenRandom(n, charType int) string
- func GetJSON(url string, v any) error
- func GetURL(url string) (reply []byte, err error)
- func HMACSHA1(s, key string) string
- func HMACSHA256(s, key string) string
- func IsEmpty(s string) bool
- func Left(s string, n int) string
- func Len(s string) int
- func LoadJSONConfig(fn string, v any) error
- func LoadXMLConfig(fn string, v any) error
- func MD5(s string) string
- func MakeDir(dir string) error
- func Mid(s string, start, length int) string
- func MustLoadConfig(fn string, v any)
- func Now() string
- func PostJSON(url string, params string) (reply []byte, err error)
- func PostURL(url string, params string) (reply []byte, err error)
- func ReadText(filepath string) (text string, err error)
- func RecoverWrap(h http.Handler) http.Handler
- func RemoteIP(r *http.Request) string
- func Right(s string, n int) string
- func RndAlpha(n int) string
- func RndFilename(ext string) string
- func RndNumber(n int) string
- func RndString(n int) string
- func SHA1(s string) string
- func SHA256(s string) string
- func Space(count int) string
- func StringToBytes(s string) []byte
- func Test(str, pattern string) bool
- func WriteText(filepath string, text string) (err error)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // RequestTimeout set the maximum time for a request. RequestTimeout time.Duration = 10 )
Functions ¶
func AppPath ¶ added in v0.0.2
func AppPath() string
AppPath returns an absolute path of app.
Example ¶
dir := AppPath() // dir is your app startup dir dir = "c:\\fakeapp" fmt.Println(dir)
Output: c:\fakeapp
func AppendText ¶
AppendText append a string to a text file.
func BytesToString ¶ added in v0.0.2
BytesToString converts a byte slice to a string. Deprecated: This function will be removed in a future version. Use the standard library's string() conversion directly instead.
func CDate ¶
CDate parses a string into a time.Time object. It accepts formats "2006-1-2 15:04:05" and "2006-1-2". Returns 1900-01-01 if the string cannot be parsed.
Example ¶
fmt.Println(CDate("1982-2-11 20:13:14").Format("2006-01-02 15:04:05"))
fmt.Println(CDate("1982-02-11 20:13:14").Format("2006-01-02 15:04:05"))
fmt.Println(CDate("1982-02-11").Format("2006-01-02 15:04:05"))
fmt.Println(CDate("82-02-11").Format("2006-01-02 15:04:05")) //unsupport
Output: 1982-02-11 20:13:14 1982-02-11 20:13:14 1982-02-11 00:00:00 1900-01-01 00:00:00
func CInt ¶
CInt converts a string to an integer. It is a wrapper around strconv.Atoi. Returns 0 if the string cannot be converted to an integer.
Example ¶
str := "456" num := CInt(str) fmt.Println(num)
Output: 456
func CStr ¶
CStr converts an integer to a string. It is a wrapper around strconv.Itoa.
Example ¶
num := 123 str := CStr(num) fmt.Println(str)
Output: 123
func DownloadFile ¶ added in v0.0.2
DownloadFile download a file from a url.
Example ¶
ms := mockServer()
defer ms.Close()
localFile := "testdata/demo.txt"
err := DownloadFile(ms.URL+"/file/demo.txt", localFile)
if err != nil {
log.Println(err)
}
os.Remove(localFile) //clean up
fmt.Println("OK")
Output: OK
func FileExist ¶ added in v0.0.2
FileExist returns true if a specified file exists; false if it does not.
Example ¶
fmt.Println(FileExist("testdata/config.json"))
fmt.Println(FileExist("testdata/notexist.txt"))
Output: true false
func FolderExist ¶ added in v0.0.2
FolderExist returns true if a specified folder exists; false if it does not.
Example ¶
fmt.Println(FolderExist("testdata"))
fmt.Println(FolderExist("testdata2"))
Output: true false
func FormatDateTime ¶ added in v0.0.2
FormatDateTime formats a time.Time according to the specified mode. Available modes are: - myDateTime: "2006-01-02 15:04:05" - myLongDate: "2006-01-02" - myShortDate: "01-02" - myLongTime: "15:04:05" - myShortTime: "15:04"
Example ¶
// 创建一个固定的时间用于示例 t := time.Date(2023, 5, 15, 14, 30, 45, 0, time.Local) // 展示不同格式的输出 fmt.Println(FormatDateTime(t, myDateTime)) fmt.Println(FormatDateTime(t, myLongDate)) fmt.Println(FormatDateTime(t, myShortDate)) fmt.Println(FormatDateTime(t, myLongTime)) fmt.Println(FormatDateTime(t, myShortTime))
Output: 2023-05-15 14:30:45 2023-05-15 05-15 14:30:45 14:30
func FriendlyTime ¶
FriendlyTime returns a human-friendly representation of the time elapsed since the given time. It returns different formats based on the elapsed time: - "刚刚" for less than a minute - "X分钟前" for less than an hour - "X小时前" for less than a day - "X天前" for less than a week - The date in "2006-01-02" format for longer periods
Example ¶
fmt.Println(FriendlyTime(time.Now().Add(-2 * time.Second)))
fmt.Println(FriendlyTime(time.Now().Add(-2 * time.Minute)))
fmt.Println(FriendlyTime(time.Now().Add(-2 * time.Hour)))
fmt.Println(FriendlyTime(time.Now().Add(-2 * 24 * time.Hour)))
longLongAgo, _ := time.Parse("2006-01-02 15:04:05", "1982-02-11 20:13:14")
fmt.Println(FriendlyTime(longLongAgo))
Output: 刚刚 2分钟前 2小时前 2天前 1982-02-11
func GetJSON ¶ added in v0.0.2
GetJSON get json from a url and unmarshal to a struct.
Example ¶
ms := mockServer()
defer ms.Close()
type Result struct {
Code int `json:"code"`
Message string `json:"message"`
Data []any `json:"data"`
Total int `json:"total"`
}
var ret Result
err := GetJSON(ms.URL+"/json", &ret)
if err != nil {
return
}
fmt.Println(ret.Code)
Output: 0
func GetURL ¶
GetURL request a url.
Example ¶
ms := mockServer()
defer ms.Close()
s, err := GetURL(ms.URL + "/ping")
if err != nil {
return
}
fmt.Println(string(s))
Output: PONG
func HMACSHA256 ¶ added in v0.0.2
HMACSHA256 generate a keyed hash value using the HMAC method.
func IsEmpty ¶
IsEmpty checks if a string is empty. Returns true if the string length is 0, false otherwise.
Example ¶
var s string fmt.Println(IsEmpty(s)) s = "zs5460" fmt.Println(IsEmpty(s))
Output: true false
func Left ¶
Left returns the first n characters from the left side of a string. If n is less than 1, returns an empty string. If n is greater than or equal to the string length, returns the entire string.
Example ¶
s := "zs5460" fmt.Println(Left(s, 2)) s = "公元2000年" fmt.Println(Left(s, 5))
Output: zs 公元200
func Len ¶
Len returns the number of Unicode code points (runes) in a string. This is different from len(s) which returns the number of bytes.
Example ¶
s := "zs5460" fmt.Println(Len(s)) s = "公元2000年" fmt.Println(Len(s))
Output: 6 7
func LoadJSONConfig ¶ added in v0.0.2
LoadJSONConfig load config from json file.
Example ¶
type config struct {
AppName string
Version string
}
var c config
err := LoadJSONConfig("testdata/config.json", &c)
if err != nil {
log.Fatal(err)
}
fmt.Println(c.AppName)
fmt.Println(c.Version)
Output: DEMO 1.0.0
func LoadXMLConfig ¶ added in v0.0.2
LoadXMLConfig load config from xml file.
Example ¶
type config struct {
AppName string `xml:"appname"`
Version string `xml:"version"`
}
var c config
err := LoadXMLConfig("testdata/config.xml", &c)
if err != nil {
log.Fatal(err)
}
fmt.Println(c.AppName)
fmt.Println(c.Version)
Output: DEMO 1.0.0
func Mid ¶
Mid returns a substring starting at the specified position with the specified length. If start is negative, it is treated as 0. If start is greater than the string length, returns an empty string. If length is less than 1, returns an empty string. If start+length exceeds the string length, returns the substring from start to the end.
Example ¶
s := "zs5460" fmt.Println(Mid(s, 2, 2)) s = "公元2000年" fmt.Println(Mid(s, 2, 4))
Output: 54 2000
func MustLoadConfig ¶ added in v0.0.2
MustLoadConfig load config or panic.
Example ¶
type config struct {
AppName string `xml:"appname"`
Version string `xml:"version"`
}
var c config
MustLoadConfig("testdata/config.xml", &c)
fmt.Println(c.AppName)
fmt.Println(c.Version)
Output: DEMO 1.0.0
func Now ¶
func Now() string
Now returns the current date and time formatted as "2006-01-02 15:04:05".
Example ¶
// 这个示例只是展示如何使用Now函数,实际输出会根据当前时间而变化
fmt.Println("Current time format:", Now())
func PostURL ¶
PostURL request a url with POST method. params is a string like k1=v1&k2=v2
Example ¶
ms := mockServer()
defer ms.Close()
s, err := PostURL(ms.URL+"/post", "name=zs")
if err != nil {
return
}
fmt.Println(string(s))
Output: name:zs
func RecoverWrap ¶ added in v0.0.8
Handler wraps the http.Handler with panic recovery support.
func Right ¶
Right returns the last n characters from the right side of a string. If n is less than 1, returns an empty string. If n is greater than or equal to the string length, returns the entire string.
Example ¶
s := "zs5460" fmt.Println(Right(s, 2)) s = "公元2000年" fmt.Println(Right(s, 5))
Output: 60 2000年
func RndFilename ¶
RndFilename returns a file name consisting of a time and a random string.
func Space ¶
Space returns a string consisting of the specified number of spaces. It is a wrapper around strings.Repeat(" ", count).
Example ¶
s := "a" + Space(5) + "b"
fmt.Println(s)
fmt.Println("1234567")
Output: a b 1234567
func StringToBytes ¶ added in v0.0.2
StringToBytes converts a string to a byte slice. Deprecated: This function will be removed in a future version. Use the standard library's []byte() conversion directly instead.
func Test ¶
Test provides some common regular expression detection features.
Example ¶
// pattern can be english,chinese,idcard,email,qq,zip,phone,mobile,url,username,password. s := "zs5460" fmt.Println(Test(s, "english")) s = "zhousong" fmt.Println(Test(s, "english")) s = "zs5460.gmail.com" fmt.Println(Test(s, "email")) s = "zs5460@gmail.com" fmt.Println(Test(s, "email"))
Output: false true false true
Types ¶
This section is empty.