utils

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2026 License: BSD-3-Clause Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DebugLevel = zap.DebugLevel
	InfoLevel  = zap.InfoLevel
	WarnLevel  = zap.WarnLevel
	ErrorLevel = zap.ErrorLevel
	FatalLevel = zap.FatalLevel
)

Variables

This section is empty.

Functions

func CustomizeDefaultHttpClient

func CustomizeDefaultHttpClient(maxIdleConns, maxIdleConnsPerHost, maxConnsPerHost int)

CustomizeDefaultHttpClient replaces http.DefaultClient with a client using the given connection pooling limits.

func DummyList

func DummyList[T any]() []T

DummyList returns a non-nil empty slice for type T.

func GenRandomToken

func GenRandomToken() (string, error)

func GetLogger

func GetLogger() *zap.SugaredLogger

GetLogger returns the global sugared logger.

func GetRawLogger

func GetRawLogger() *zap.Logger

GetRawLogger returns the underlying zap.Logger instance.

func HandleRestfulResponse

func HandleRestfulResponse(resp *http.Response, obj any) (code int, err error)

HandleRestfulResponse decodes an HTTP response into obj. When obj is nil it discards the body; when obj is *[]byte it returns the raw body.

func HttpChangeLogLevel

func HttpChangeLogLevel(w http.ResponseWriter, r *http.Request)

HttpChangeLogLevel changes the global log level based on the request body. It accepts DEBUG/INFO/WARN/ERROR (case-insensitive).

func HttpGetJsonArgs

func HttpGetJsonArgs(r *http.Request, obj any) error

HttpGetJsonArgs decodes a JSON request body into obj without logging.

func HttpGetJsonArgsWithLog

func HttpGetJsonArgsWithLog(logger *ContextLogger, r *http.Request, obj any) error

HttpGetJsonArgsWithLog decodes a JSON body into obj and logs the raw payload.

func HttpGetPbArgs

func HttpGetPbArgs(r *http.Request, m proto.Message) (bin bool, err error)

HttpGetPbArgs reads a protobuf request into m. When Content-Type is application/json it expects JSON, otherwise protobuf wire format.

func HttpReplyJson

func HttpReplyJson(w http.ResponseWriter, code int, obj any) error

HttpReplyJson writes obj as JSON response with the given HTTP status code.

func HttpReplyJsonWithLog

func HttpReplyJsonWithLog(logger *ContextLogger, w http.ResponseWriter, code int, obj any) error

HttpReplyJsonWithLog writes obj as JSON and logs the raw payload.

func HttpReplyPb

func HttpReplyPb(w http.ResponseWriter, code int, m proto.Message, bin bool) (err error)

HttpReplyPb writes a protobuf message as either JSON or protobuf wire format.

func IncrWithTTL

func IncrWithTTL(ctx context.Context, db *redis.Client, key string, ttlSeconds int64) (int64, error)

func InitLog

func InitLog(path string, maxBackups, maxDays int)

InitLog initializes the global logger writing JSON logs to the given path. Repeated calls after initialization are ignored.

func IsMysqlDuplicateError

func IsMysqlDuplicateError(err error) bool

IsMysqlDuplicateError reports whether err represents a MySQL duplicate key error.

func ListIntoSet

func ListIntoSet[T comparable](list []T, set map[T]bool)

ListIntoSet inserts all elements of list into set.

func ListToSet

func ListToSet[T comparable](list []T) map[T]bool

ListToSet builds a map-based set from list with all elements set to true.

func LoadJsonFile

func LoadJsonFile(filepath string, obj any) error

LoadJsonFile reads a JSON file from filepath and decodes it into obj. obj must be a pointer to the target value.

func LoadYamlFile

func LoadYamlFile(filepath string, obj any) error

LoadYamlFile reads a YAML file from filepath and decodes it into obj. obj must be a pointer to the target value.

func LogLevelEnabled

func LogLevelEnabled(lv LogLevel) bool

LogLevelEnabled reports whether the given level is enabled on the global logger.

func MaybeMetrisName

func MaybeMetrisName(name string) bool

MaybeMetrisName reports whether name is a valid Prometheus metric name.

func NewCounter

func NewCounter(name string) prometheus.Counter

NewCounter creates a Counter with the given metric name.

func NewCounterVec

func NewCounterVec(name string, labelNames ...string) *prometheus.CounterVec

NewCounterVec creates a CounterVec with the given metric name.

func NewGauge

func NewGauge(name string) prometheus.Gauge

NewGauge creates a Gauge with the given metric name.

func NewGaugeVec

func NewGaugeVec(name string, labelNames ...string) *prometheus.GaugeVec

NewGaugeVec creates a GaugeVec with the given metric name.

func NewRedisClient

func NewRedisClient(cfg *RedisConfig) *redis.Client

func NewRedisClientWithCheck

func NewRedisClientWithCheck(cfg *RedisConfig) (*redis.Client, error)

func NewRestfulRequest

func NewRestfulRequest(ctx context.Context, method, url string,
	headers, params map[string]string, obj any) (*http.Request, error)

NewRestfulRequest builds an HTTP request with optional JSON body and headers/params. If obj is *[]byte the raw bytes are sent as the request body.

func NewSummary

func NewSummary(name string) prometheus.Summary

NewSummary creates a Summary with preset objectives.

func NewSummaryVec

func NewSummaryVec(name string, labelNames ...string) *prometheus.SummaryVec

NewSummaryVec creates a SummaryVec with preset objectives.

func OverwriteMysqlParams

func OverwriteMysqlParams(config string, patch map[string]string) string

OverwriteMysqlParams overwrites or adds query parameters on a MySQL DSN.

func RecordLatencyUs

func RecordLatencyUs(s prometheus.Observer, begin time.Time)

RecordLatencyUs observes the elapsed time since begin in microseconds.

func ReplaceNilByDummy

func ReplaceNilByDummy[T any](list []T) []T

ReplaceNilByDummy converts a nil slice to a non-nil empty slice.

func RestfulDelete

func RestfulDelete(ctx context.Context, url string,
	headers, params map[string]string) (code int, err error)

RestfulDelete sends an HTTP DELETE request and discards the response body.

func RestfulDo

func RestfulDo(ctx context.Context, method, url string,
	headers, params map[string]string, obj, out any) (code int, err error)

RestfulDo sends an HTTP request and decodes the response into out.

func RestfulGet

func RestfulGet(ctx context.Context, url string,
	headers, params map[string]string, out any) (code int, err error)

RestfulGet sends an HTTP GET request and decodes the response into out.

func RestfulPatch

func RestfulPatch(ctx context.Context, url string,
	headers, params map[string]string, obj any) (code int, err error)

RestfulPatch sends an HTTP PATCH with an optional JSON body.

func RestfulPost

func RestfulPost(ctx context.Context, url string,
	headers, params map[string]string, obj, out any) (code int, err error)

RestfulPost sends an HTTP POST with an optional JSON body and decodes response into out.

func RestfulPut

func RestfulPut(ctx context.Context, url string,
	headers, params map[string]string, obj any) (code int, err error)

RestfulPut sends an HTTP PUT with an optional JSON body.

func RunHttpServer

func RunHttpServer(router http.Handler, address string) error

RunHttpServer starts an HTTP server on address and shuts it down on SIGINT/SIGTERM.

func SetLogLevel

func SetLogLevel(lv LogLevel)

SetLogLevel updates the global logger level at runtime.

func SqlCreate

func SqlCreate(ctx context.Context, stmt *sql.Stmt, args ...any) (int64, error)

SqlCreate executes an INSERT statement and returns the last inserted ID.

func SqlModify

func SqlModify(ctx context.Context, stmt *sql.Stmt, args ...any) (int64, error)

SqlModify executes an UPDATE/DELETE statement and returns rows affected.

func SyncLog

func SyncLog()

SyncLog flushes buffered log entries to the underlying writer.

func TryRegisterMetris

func TryRegisterMetris(r *prometheus.Registry, m prometheus.Collector)

TryRegisterMetris registers a collector and logs the error instead of failing.

func TryToConvertMetrisName

func TryToConvertMetrisName(name string) (string, error)

TryToConvertMetrisName converts a string into a Prometheus metric name if possible.

func UnsafeBytesToString

func UnsafeBytesToString(b []byte) string

UnsafeBytesToString converts a byte slice to string without allocation. The returned string must not be used after b is modified.

func UnsafeStringToBytes

func UnsafeStringToBytes(s string) []byte

UnsafeStringToBytes converts a string to a byte slice without allocation. The returned slice must be treated as read-only to avoid breaking string immutability.

Types

type ActionMetrics

type ActionMetrics struct {
	Count   prometheus.Counter
	Failure prometheus.Counter
	Latency prometheus.Summary
}

ActionMetrics bundles common metrics for counting, failures and latency.

func (*ActionMetrics) Init

func (m *ActionMetrics) Init(prefix string)

Init initializes metrics with the given name prefix.

func (*ActionMetrics) MustRegister

func (m *ActionMetrics) MustRegister(registry *prometheus.Registry)

MustRegister registers metrics in the registry and panics on failure.

func (*ActionMetrics) Register

func (m *ActionMetrics) Register(registry *prometheus.Registry)

Register registers metrics in the registry and ignores registration errors.

type ContextLogger

type ContextLogger struct {
	// contains filtered or unexported fields
}

ContextLogger logs with a unique trace sn and optional context label.

func NewContextLogger

func NewContextLogger(ctx string) *ContextLogger

NewContextLogger returns a ContextLogger with the provided context label.

func (*ContextLogger) Debug

func (l *ContextLogger) Debug(msg string)

Debug logs a debug message with the context trace fields.

func (*ContextLogger) Debugf

func (l *ContextLogger) Debugf(tpl string, args ...any)

Debugf formats and logs a debug message when debug level is enabled.

func (*ContextLogger) Error

func (l *ContextLogger) Error(msg string)

Error logs an error message with the context trace fields.

func (*ContextLogger) Errorf

func (l *ContextLogger) Errorf(tpl string, args ...any)

Errorf formats and logs an error message when error level is enabled.

func (*ContextLogger) Info

func (l *ContextLogger) Info(msg string)

Info logs an info message with the context trace fields.

func (*ContextLogger) Infof

func (l *ContextLogger) Infof(tpl string, args ...any)

Infof formats and logs an info message when info level is enabled.

func (*ContextLogger) Warn

func (l *ContextLogger) Warn(msg string)

Warn logs a warning message with the context trace fields.

func (*ContextLogger) Warnf

func (l *ContextLogger) Warnf(tpl string, args ...any)

Warnf formats and logs a warning message when warn level is enabled.

type LogLevel

type LogLevel = zapcore.Level

LogLevel is an alias of zapcore.Level for log level configuration.

type RedisConfig

type RedisConfig struct {
	Address  string `json:"address" yaml:"address"`
	Password string `json:"password" yaml:"password"`
	PoolSize int    `json:"pool_size" yaml:"pool_size"`
	IdleSize int    `json:"idle_size" yaml:"idle_size"`
}

type Xorshift

type Xorshift struct {
	// contains filtered or unexported fields
}

Xorshift implements a simple 32-bit xorshift pseudo-random generator.

func (*Xorshift) Init

func (xs *Xorshift) Init(seed uint32)

Init initializes the generator with the given seed.

func (*Xorshift) Next

func (xs *Xorshift) Next() uint32

Next returns the next pseudo-random value.

Jump to

Keyboard shortcuts

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