Skip to content

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

go
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:

go
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.

FieldTypeJSON TagDescription
Codeint"code"Status code, 0 indicates success
Msgstring"msg"Message content, can be empty on success
Dataany"data"Return data, can be any type

Example:

go
// 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:

ParameterTypeRequiredDescription
pathstringYesAbsolute/relative path of the file or directory

Returns: booltrue if file exists, false if it doesn't

Example:

go
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:

ParameterTypeRequiredDescription
pathstringYesPath to check

Returns: booltrue if it's a directory, false if not a directory or path doesn't exist

Example:

go
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:

ParameterTypeRequiredDescription
lengthintYesLength of the generated string

Returns: string — random string containing lowercase letters and digits

Example:

go
// 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:

ParameterTypeRequiredDescription
strstringYesString to search for
strs[]stringYesTarget string slice

Returns: booltrue if found, false if not found

Example:

go
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:

ParameterTypeRequiredDescription
slice[]stringYesTarget string slice
strstringYesString to search for

Returns: booltrue if found, false if not found

Example:

go
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:

ParameterTypeRequiredDescription
slice[]stringYesString slice to deduplicate

Returns: []string — deduplicated string slice

Example:

go
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:

ParameterTypeRequiredDescription
srcmap[string]anyYesSource Map, provides the key-value pairs to merge
tgtmap[string]anyYesTarget Map, receives the merge result
itgtmap[any]anyNoOptional intermediate Map, synchronously receives the merge result; pass nil to skip

Returns: None (directly modifies tgt and itgt)

Example:

go
// 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 true

RandomSleep(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:

ParameterTypeRequiredDescription
minMillsintYesMinimum sleep time (milliseconds)
maxMillsintYesMaximum sleep time (milliseconds)

Returns: None

Example:

go
// 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:

ParameterTypeRequiredDescription
minintYesLower bound of random number (inclusive)
maxintYesUpper bound of random number (exclusive)

Returns: int — random integer within the range

Example:

go
// Generate a random number from 1-100
num := ehelper.Int(1, 100)
fmt.Println("Random number:", num)

See also: RandomSleep()