my

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2026 License: MIT Imports: 19 Imported by: 3

README

my

Build Status Go Report Card codecov GoDoc

my utility package

Install

go get -u github.com/zs5460/my

License

Released under MIT license, see LICENSE for details.

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

Examples

Constants

This section is empty.

Variables

View Source
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.

func AppendText

func AppendText(filepath string, text string) (err error)

AppendText append a string to a text file.

func BytesToString added in v0.0.2

func BytesToString(b []byte) string

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

func CDate(s string) time.Time

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

func CInt(s string) int

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

func CStr(i int) string

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 ClientIP added in v0.0.9

func ClientIP(r *http.Request) string

ClientIP

func DownloadFile added in v0.0.2

func DownloadFile(url, filepath string) (err error)

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

func FileExist(path string) bool

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

func FolderExist(path string) bool

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

func FormatDateTime(t time.Time, mode dateTimeFormat) string

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

func FriendlyTime(t time.Time) string

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 GenRandom added in v0.0.2

func GenRandom(n, charType int) string

GenRandom ...

func GetJSON added in v0.0.2

func GetJSON(url string, v any) error

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

func GetURL(url string) (reply []byte, err error)

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 HMACSHA1

func HMACSHA1(s, key string) string

HMACSHA1 generate a keyed hash value using the HMAC method.

func HMACSHA256 added in v0.0.2

func HMACSHA256(s, key string) string

HMACSHA256 generate a keyed hash value using the HMAC method.

func IsEmpty

func IsEmpty(s string) bool

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

func Left(s string, n int) string

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

func Len(s string) int

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

func LoadJSONConfig(fn string, v any) error

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

func LoadXMLConfig(fn string, v any) error

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 MD5

func MD5(s string) string

MD5 calculate the md5 hash of a string.

func MakeDir added in v0.0.2

func MakeDir(dir string) error

MakeDir creates a folder.

func Mid

func Mid(s string, start, length int) string

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

func MustLoadConfig(fn string, v any)

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 PostJSON added in v0.0.3

func PostJSON(url string, params string) (reply []byte, err error)

PostJSON request a url with POST method params is a json string

func PostURL

func PostURL(url string, params string) (reply []byte, err error)

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 ReadText

func ReadText(filepath string) (text string, err error)

ReadText reads an entire text file and returns the resulting string.

func RecoverWrap added in v0.0.8

func RecoverWrap(h http.Handler) http.Handler

Handler wraps the http.Handler with panic recovery support.

func RemoteIP added in v0.0.9

func RemoteIP(r *http.Request) string

RemoteIP

func Right(s string, n int) string

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 RndAlpha

func RndAlpha(n int) string

RndAlpha returns a string of letters of the specified length.

func RndFilename

func RndFilename(ext string) string

RndFilename returns a file name consisting of a time and a random string.

func RndNumber

func RndNumber(n int) string

RndNumber returns a string of numbers of the specified length.

func RndString

func RndString(n int) string

RndString returns a random string of the specified length.

func SHA1

func SHA1(s string) string

SHA1 calculate the sha1 hash of a string.

func SHA256

func SHA256(s string) string

SHA256 calculate the sha256 hash of a string.

func Space

func Space(count int) string

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

func StringToBytes(s string) []byte

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

func Test(str, pattern string) bool

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

func WriteText

func WriteText(filepath string, text string) (err error)

WriteText writes a specified string to a text file.

Types

This section is empty.

Jump to

Keyboard shortcuts

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