Introduction
ehelper is the utility function module of ee-go, providing common helper features including JSON return value construction, file/directory detection, random string generation, string contains checking, slice deduplication, Map merging, random delay, and random integer generation. These functions cover the most common basic operations in application development, reducing repetitive code writing.
Import
import "github.com/wallace5303/ee-go/ehelper"API
GetJson()
Description: Create a standard JSON return value struct with default Code as 0, Msg as empty string, and Data as nil. Used for unified HTTP response format.
Parameters: None
Returns: *ResultJson — initialized JSON result struct pointer
Example:
result := ehelper.GetJson()
result.Code = 0
result.Msg = "success"
result.Data = map[string]any{
"id": 1,
"name": "example",
}
// Return to frontend
c.JSON(200, result)See also: ResultJson
ResultJson
Description: Unified JSON response struct for HTTP interface return data. Contains three fields: status code, message, and data. Field names are mapped to lowercase via JSON tags.
| Field | Type | JSON Tag | Description |
|---|---|---|---|
| Code | int | "code" | Status code, 0 indicates success |
| Msg | string | "msg" | Message content, can be empty on success |
| Data | any | "data" | Return data, can be any type |
Example:
// Custom response
r := &ehelper.ResultJson{
Code: -1,
Msg: "parameter error",
Data: nil,
}FileIsExist(path)
Description: Check whether a file or directory exists at the specified path. Returns true if the path exists, false if it doesn't.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| path | string | Yes | Absolute/relative path of the file or directory |
Returns: bool — true if file exists, false if it doesn't
Example:
configPath := "/opt/app/config.json"
if ehelper.FileIsExist(configPath) {
// Read configuration
} else {
// Use default configuration
}IsDir(path)
Description: Check whether the specified path is a directory. Returns false if the path doesn't exist or is not a directory.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| path | string | Yes | Path to check |
Returns: bool — true if it's a directory, false if not a directory or path doesn't exist
Example:
path := "/opt/app/data"
if ehelper.IsDir(path) {
fmt.Println("data is a directory")
} else {
os.MkdirAll(path, 0755)
}See also: FileIsExist()
GetRandomString(length)
Description: Generate a random string of specified length, with character range including lowercase letters a-z and digits 0-9. There is a 10ns interval between calls to ensure randomness.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| length | int | Yes | Length of the generated string |
Returns: string — random string containing lowercase letters and digits
Example:
// Generate a 16-character random string
token := ehelper.GetRandomString(16)
fmt.Println("Token:", token) // e.g.: "a3b7c9d2e5f8g1h4"Contains(str, strs)
Description: Check whether string str exists in the string slice strs. Compares sequentially, returns true on first match.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| str | string | Yes | String to search for |
| strs | []string | Yes | Target string slice |
Returns: bool — true if found, false if not found
Example:
events := []string{"beforeClose", "ready"}
if ehelper.Contains("beforeClose", events) {
fmt.Println("event is supported")
}See also: SlicesContains()
SlicesContains(slice, str)
Description: Check whether string str exists in the string slice slice. Same functionality as Contains() with different naming style. This function is used uniformly within the framework.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| slice | []string | Yes | Target string slice |
| str | string | Yes | String to search for |
Returns: bool — true if found, false if not found
Example:
validEvents := []string{"beforeClose"}
if ehelper.SlicesContains(validEvents, eventName) {
// Register event
}See also: Contains()
RemoveDuplicatedElem(slice)
Description: Remove duplicate elements from a string slice, keeping the first occurrence of each element, and return the deduplicated new slice. The original slice is not modified.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| slice | []string | Yes | String slice to deduplicate |
Returns: []string — deduplicated string slice
Example:
names := []string{"alice", "bob", "alice", "charlie", "bob"}
unique := ehelper.RemoveDuplicatedElem(names)
fmt.Println(unique) // ["alice", "bob", "charlie"]Mapserge(src, tgt, itgt)
Description: Merge source Map src into target Map tgt. For keys that already exist in the target Map, if the value is a Map type it is recursively merged, otherwise the source value overwrites the target value. Key name matching is case-insensitive. The optional itgt parameter (type map[any]any) synchronously receives the merge result, for compatibility with Viper's internal map[any]any type data.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| src | map[string]any | Yes | Source Map, provides the key-value pairs to merge |
| tgt | map[string]any | Yes | Target Map, receives the merge result |
| itgt | map[any]any | No | Optional intermediate Map, synchronously receives the merge result; pass nil to skip |
Returns: None (directly modifies tgt and itgt)
Example:
// Configuration merge: merge environment configuration into default configuration
defaultCfg := map[string]any{
"http": map[string]any{
"port": 8080,
"enable": true,
},
}
envCfg := map[string]any{
"http": map[string]any{
"port": 9090,
},
}
ehelper.Mapserge(envCfg, defaultCfg, nil)
// defaultCfg["http"]["port"] is overwritten to 9090
// defaultCfg["http"]["enable"] remains trueRandomSleep(minMills, maxMills)
Description: Randomly sleep within a specified time range. Sleep duration is a random value between [minMills, maxMills) milliseconds. Suitable for avoiding concentrated concurrent requests, simulating delay, and similar scenarios.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| minMills | int | Yes | Minimum sleep time (milliseconds) |
| maxMills | int | Yes | Maximum sleep time (milliseconds) |
Returns: None
Example:
// Randomly sleep 100-500 milliseconds
ehelper.RandomSleep(100, 500)See also: Int()
Int(min, max)
Description: Generate a random integer in the range [min, max). There is a 10ns interval between calls to ensure randomness.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| min | int | Yes | Lower bound of random number (inclusive) |
| max | int | Yes | Upper bound of random number (exclusive) |
Returns: int — random integer within the range
Example:
// Generate a random number from 1-100
num := ehelper.Int(1, 100)
fmt.Println("Random number:", num)See also: RandomSleep()
