help

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2026 License: BSD-3-Clause Imports: 28 Imported by: 2

Documentation

Overview

Package help provides common utility functions for Go applications.

It includes:

  • Random string generation (cryptographically secure)
  • UUID and Snowflake ID generation
  • Slice/string manipulation (reverse, shuffle)
  • Map to query string conversion
  • SM2/SM4 cryptographic utilities
  • Hertz framework integration helpers

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrSM2InvalidPublicKey  = errors.New("sm2: invalid public key format")
	ErrSM2InvalidPrivateKey = errors.New("sm2: invalid private key format")
	ErrSM2InvalidSignature  = errors.New("sm2: invalid signature format")
)

SM2 related errors.

View Source
var (
	ErrSM4InvalidKey        = errors.New("sm4: invalid key, must be 32 hex characters (16 bytes)")
	ErrSM4InvalidCiphertext = errors.New("sm4: invalid ciphertext")
	ErrSM4InvalidPadding    = errors.New("sm4: invalid PKCS5 padding")
	ErrSM4EmptyData         = errors.New("sm4: data is empty")
)

SM4 related errors.

View Source
var ErrorTypePublic = errors.ErrorTypePublic

ErrorTypePublic is the type for public errors in Hertz framework.

SF is a global Sonyflake instance for generating distributed unique IDs. Sonyflake generates 63-bit unique IDs inspired by Twitter's Snowflake.

View Source
var SM2UID = []byte{0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38}

SM2UID is the default user ID for SM2 signing/verification. This is the standard 16-byte UID "1234567812345678".

Functions

func E

func E(code int64, msg string) *errors.Error

E creates a public Hertz error with a code. Use this for business logic errors that should be shown to users.

func ErrorHandler

func ErrorHandler() app.HandlerFunc

ErrorHandler returns a Hertz middleware that handles errors. It processes different error types:

  • Public errors: Returns 400 with code and message
  • Validation errors: Returns 400 with field details
  • Other errors: Returns 500 (with details in dev mode)

Set MODE=release environment variable for production mode.

func HmacSha256

func HmacSha256(s, key string) string

HmacSha256 computes HMAC-SHA256 and returns raw bytes as string. For hex output, use hex.EncodeToString on the result.

func IsEmpty

func IsEmpty(i any) bool

IsEmpty checks if a value is considered empty. Returns true for nil, empty strings, zero values, empty slices/maps, etc.

func MapToSignText

func MapToSignText(d map[string]any) string

MapToSignText converts a map to a URL-encoded query string format. Keys are sorted alphabetically, nil and empty values are omitted. Format: "key1=value1&key2=value2"

func PrivKeySM2FromBase64

func PrivKeySM2FromBase64(v string) (*sm2.PrivateKey, error)

PrivKeySM2FromBase64 parses a base64-encoded SM2 private key. The key should be in PKCS8 format (DER encoded, then base64).

func Ptr

func Ptr[T any](i T) *T

Ptr returns a pointer to the given value. Useful for creating pointers to literals.

func PubKeySM2FromBase64

func PubKeySM2FromBase64(v string) (*ecdsa.PublicKey, error)

PubKeySM2FromBase64 parses a base64-encoded SM2 public key. The key should be in PKIX format (DER encoded, then base64).

func Random

func Random(n int, charset ...string) string

Random generates a cryptographically secure random string of length n. By default, it uses alphanumeric characters (a-zA-Z0-9). An optional charset can be provided to customize the character set.

func RandomAlphabet

func RandomAlphabet(n int) string

RandomAlphabet generates a random alphabetic string of length n. Uses both uppercase and lowercase letters.

func RandomLowercase

func RandomLowercase(n int) string

RandomLowercase generates a random lowercase alphabetic string of length n.

func RandomNumber

func RandomNumber(n int) string

RandomNumber generates a random numeric string of length n. Uses only digits 0-9.

func RandomUppercase

func RandomUppercase(n int) string

RandomUppercase generates a random uppercase alphabetic string of length n.

func Reverse

func Reverse[T any](v []T)

Reverse reverses the order of elements in a slice in place.

func ReverseString

func ReverseString(v string) string

ReverseString returns a new string with characters in reverse order. Properly handles Unicode characters.

func SID

func SID() string

SID generates a new Sonyflake ID as a string. Returns an empty string if ID generation fails. Note: In high-availability scenarios, consider using SIDWithError instead.

func SIDWithError added in v1.0.0

func SIDWithError() (string, error)

SIDWithError generates a new Sonyflake ID as a string. Returns the ID and any error that occurred during generation.

func SM4Decrypt

func SM4Decrypt(hexkey string, ciphertext string) (string, error)

SM4Decrypt decrypts ciphertext using SM4-ECB mode with PKCS5 padding. The key must be a 32-character hex string (16 bytes). The ciphertext must be hex-encoded. Returns the decrypted plaintext.

func SM4Encrypt

func SM4Encrypt(hexkey string, plaintext string) (string, error)

SM4Encrypt encrypts plaintext using SM4-ECB mode with PKCS5 padding. The key must be a 32-character hex string (16 bytes). Returns hex-encoded ciphertext.

func SM4Verify

func SM4Verify(key string, ciphertext string, plaintext string) (bool, error)

SM4Verify decrypts and compares ciphertext with expected plaintext. Returns true if the decrypted text matches the plaintext.

func Sha256hex

func Sha256hex(s string) string

Sha256hex computes SHA256 hash and returns hex-encoded string.

func Shuffle

func Shuffle[T any](v []T)

Shuffle randomly shuffles the elements in a slice in place. Uses cryptographically secure random numbers.

func ShuffleString

func ShuffleString(v string) string

ShuffleString returns a new string with characters randomly shuffled. Uses cryptographically secure random numbers.

func Sm2Sign

func Sm2Sign(key *sm2.PrivateKey, text string) (string, error)

Sm2Sign signs text using SM2 private key. Returns base64-encoded ASN.1 DER signature.

func Sm2Verify

func Sm2Verify(pubKey *ecdsa.PublicKey, text string, sign string) (bool, error)

Sm2Verify verifies a signature using SM2 public key. The signature should be base64-encoded ASN.1 DER format. Returns true if the signature is valid.

func Uuid

func Uuid() string

Uuid generates a new UUID v4 string. Returns a string in the format "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".

func Validator deprecated

func Validator() *vd.Validator

Validator creates a configured go-playground validator for Hertz. It sets "vd" as the validation tag and registers custom validators:

  • snake: validates snake_case format (e.g., "user_name")
  • sort: validates sort format (e.g., "created_at:1" or "name:-1")

Deprecated: Use vd.Default() instead.

Types

type ErrorMeta

type ErrorMeta struct {
	Code int64
}

ErrorMeta contains error metadata for Hertz errors.

type R

type R struct {
	Code    int64  `json:"code"`
	Message string `json:"message"`
}

R is a standard API response structure.

func Fail

func Fail(code int64, msg string) R

Fail returns an error response with the given code and message.

func Ok

func Ok() R

Ok returns a success response with code 0 and message "ok".

Jump to

Keyboard shortcuts

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