utils

package
v1.0.47 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2025 License: MIT Imports: 23 Imported by: 2

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CastBool

func CastBool(value interface{}) bool

CastBool attempts to cast an interface{} to a bool. It supports the following types: - bool: returns the value directly. - int, int64, float64: returns true if the value is non-zero, false otherwise. - string: attempts to parse the string as a boolean using strconv.ParseBool. For any other type or if parsing fails, it returns false.

Parameters:

  • value: The value to be cast to bool.

Returns:

  • The bool representation of the value, or false if the value cannot be cast.

func CastFloat64

func CastFloat64(value interface{}) float64

CastFloat64 attempts to cast an interface{} to a float64. It supports the following types: int, int64, float64, and string. If the value is a string, it tries to parse it as a float64. If the conversion is not possible, it returns 0.

Parameters:

  • value: The value to be cast to float64.

Returns:

  • The float64 representation of the value, or 0 if the value cannot be cast.

func CastInt64

func CastInt64(value interface{}) int64

CastInt64 attempts to cast a given interface{} value to an int64. It supports the following types: int, int64, float64, and string. If the value is a string, it tries to parse it as an int64. If the value cannot be cast to int64, it returns 0.

Parameters:

  • value: The value to be cast to int64.

Returns:

  • The int64 representation of the value, or 0 if the value cannot be cast.

func CastString

func CastString(value interface{}) string

CastString attempts to cast an interface{} to a string. If the value is already a string, it returns the value directly. Otherwise, it converts the value to a string using fmt.Sprintf.

Parameters:

  • value: The interface{} value to be cast to a string.

Returns:

  • A string representation of the input value.

func ChannelStatus added in v1.0.33

func ChannelStatus[T any](channel chan T)

func DoReq

func DoReq[response any](url string, data []byte, method string, headers map[string]string) (response, int, error)

DoReq sends an HTTP request and processes the response.

This function sends an HTTP request to the specified URL with the given method, data, and headers. It returns the response body unmarshalled into the specified response type, the HTTP status code, and an error if any occurred during the process.

Type Parameters:

  • response: The type into which the response body will be unmarshalled.

Parameters:

  • url: The URL to which the request is sent.
  • data: The request payload as a byte slice.
  • method: The HTTP method to use for the request (e.g., "GET", "POST").
  • headers: A map of headers to include in the request.

Returns:

  • response: The response body unmarshalled into the specified type.
  • int: The HTTP status code of the response.
  • error: An error if any occurred during the request or response processing, otherwise nil.

func Download

func Download(url, file string) error

Download downloads the content from the specified URL and saves it to the specified file. It returns an error if any error occurs during the process.

Parameters:

  • url: The URL from which to download the content.
  • file: The path to the file where the content should be saved.

Returns:

  • error: An error object if an error occurs, otherwise nil.

func GetMainIP

func GetMainIP() (string, error)

GetMainIP retrieves the main IP address of the local machine by establishing a UDP connection to a remote server (Google's public DNS server in this case). It returns the IP address as a string and an error if any error occurs during the process.

Returns:

  • string: The main IP address of the local machine.
  • error: An error object if there is an issue obtaining the IP address.

func GetValueOf

func GetValueOf(value gjson.Result) interface{}

GetValueOf returns the Go representation of a gjson.Result value. It converts the gjson.Result to the appropriate Go type based on its type: - For gjson.String, it returns a string. - For gjson.Number, it returns an int if the value is an integer, or a float if it contains a decimal point or a comma. - For gjson.True, it returns true. - For gjson.False, it returns false. - For gjson.JSON, it returns the raw JSON string. - For any other type, it returns an empty string.

func ListFiles

func ListFiles(route string, filter string) []string

ListFiles walks through the directory specified by the route and returns a slice of file paths that match the given filter. The filter should be a file extension (e.g., ".txt").

Parameters:

  • route: The root directory to start the file search.
  • filter: The file extension to filter files by.

Returns:

  • A slice of strings containing the paths of the files that match the filter.

If an error occurs during the file walk, it logs the error and panics if the error is not "no such file or directory".

func PointerOf

func PointerOf[t any](s t) *t

PointerOf takes a value of any type and returns a pointer to that value. This is useful for creating pointers to literals or values that are not already pointers.

Example usage:

intValue := 42
intPointer := PointerOf(intValue)

Type Parameters:

t: The type of the value to be pointed to.

Parameters:

s: The value to create a pointer for.

Returns:

A pointer to the provided value.

func ReadCSV

func ReadCSV(url string) ([][]string, error)

ReadCSV reads a CSV file from the given URL and returns its contents as a slice of string slices. If an error occurs while opening or reading the file, it logs the error and returns nil.

Parameters:

  • url: The path to the CSV file.

Returns:

  • [][]string: The contents of the CSV file.
  • error: An error object if an error occurs, otherwise nil.

func ReadJSON

func ReadJSON[t any](f string) (*t, error)

ReadJSON reads a JSON file and parses its content into a specified type. The function takes a file path as input and returns a pointer to the parsed value of the specified type and a pointer to an error if an error occurs.

Type Parameters:

t: The type into which the JSON content should be parsed.

Parameters:

f: The file path of the JSON file to be read.

Returns:

*t: A pointer to the parsed value of the specified type.
error: An error object if any error occurs during the process.

func ReadPbYaml

func ReadPbYaml(f string) ([]byte, error)

ReadPbYaml reads a YAML file, converts its content to JSON, and returns the JSON bytes. If an error occurs while reading the file or converting its content, it returns an error.

Parameters:

  • f: The file path of the YAML file to be read.

Returns:

  • []byte: The JSON bytes converted from the YAML file.
  • error: An error object if an error occurs, otherwise nil.

func ReadYaml

func ReadYaml[t any](f string, jsonMode bool) (*t, error)

ReadYaml reads a YAML file and converts its content into a specified type. The function can also handle JSON mode if specified.

Type Parameters:

t: The type into which the YAML content will be converted.

Parameters:

f: The file path to the YAML file.
jsonMode: A boolean flag indicating whether to use JSON mode for conversion.

Returns:

*t: A pointer to the converted content of type t.
error: A pointer to an error object if an error occurs, otherwise nil.

func SanitizeField

func SanitizeField(s *string)

func ToObject

func ToObject(str *string, object protoreflect.ProtoMessage) error

ToObject parses a JSON-encoded string into a given ProtoMessage object.

Parameters:

  • str: A pointer to the JSON-encoded string.
  • object: The ProtoMessage object to unmarshal the JSON string into.

Returns:

  • error: An error object if the unmarshalling fails, otherwise nil.

func ToString

func ToString(object protoreflect.ProtoMessage) (*string, error)

ToString converts a given ProtoMessage object to its JSON string representation. It returns a pointer to the JSON string and a pointer to an error if any error occurs during marshaling.

Parameters:

  • object: The ProtoMessage object to be converted.

Returns:

  • *string: A pointer to the JSON string representation of the object.
  • *error: A pointer to an error if an error occurs, otherwise nil.

func ValidateFilePath

func ValidateFilePath(path string) error

ValidateFilePath validates the file path to ensure it does not contain any invalid characters or directory traversal attempts

func ValidateReservedField

func ValidateReservedField(f string, allowEmpty bool) error

ValidateReservedField validates a field to ensure it is not empty or a reserved field.

Types

type Folder added in v1.0.10

type Folder string

func MkdirJoin added in v1.0.8

func MkdirJoin(f ...string) (Folder, error)

MkdirJoin creates a directory structure specified by the joined path of given parts and returns the complete path. It uses `os.MkdirAll` with a default permission of 0755 for creating directories. Returns the resulting path and an error if any occurs during directory creation.

func (*Folder) FileJoin added in v1.0.10

func (folder *Folder) FileJoin(file string) string

FileJoin concatenates folder and file components into a single path using platform-specific path separators.

func (*Folder) String added in v1.0.10

func (folder *Folder) String() string

String returns the string representation of the Folder type.

type Meter

type Meter struct {
	StartTime time.Time
	Function  string
	Options   MeterOptions
	// contains filtered or unexported fields
}

Meter represents a structure to measure the execution time of a function. It contains the start time, the name of the function, and additional options.

func NewMeter

func NewMeter(function string, options ...MeterOptions) *Meter

NewMeter creates a new Meter instance to measure the execution time of a function. It takes a function name as a string and an optional list of MeterOptions. If no options are provided, it defaults to logging slow executions with a threshold of 50 milliseconds.

Parameters:

  • function: The name of the function to be measured.
  • options: Optional MeterOptions to customize the behavior of the Meter.

Returns:

A pointer to a Meter instance.

func (*Meter) Elapsed

func (m *Meter) Elapsed(point string) time.Duration

Elapsed calculates the duration since the Meter's StartTime. If the LogSlow option is enabled and the elapsed time exceeds the configured threshold, it logs an informational message indicating that the function is slow. Returns the elapsed time as a time.Duration.

func (*Meter) Reset

func (m *Meter) Reset()

Reset sets the StartTime of the Meter to the current time. This method is typically used to reset the timing metrics.

type MeterOptions

type MeterOptions struct {
	LogSlow       bool
	SlowThreshold time.Duration
}

MeterOptions defines the configuration options for metering. It includes options to log slow operations and set a threshold for what is considered slow.

Fields:

LogSlow: A boolean indicating whether to log operations that are considered slow.
SlowThreshold: A time.Duration value that specifies the threshold duration for slow operations.

Jump to

Keyboard shortcuts

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