Documentation
¶
Index ¶
- Constants
- func CustomizeDefaultHttpClient(maxIdleConns, maxIdleConnsPerHost, maxConnsPerHost int)
- func DummyList[T any]() []T
- func GenRandomToken() (string, error)
- func GetLogger() *zap.SugaredLogger
- func GetRawLogger() *zap.Logger
- func HandleRestfulResponse(resp *http.Response, obj any) (code int, err error)
- func HttpChangeLogLevel(w http.ResponseWriter, r *http.Request)
- func HttpGetJsonArgs(r *http.Request, obj any) error
- func HttpGetJsonArgsWithLog(logger *ContextLogger, r *http.Request, obj any) error
- func HttpGetPbArgs(r *http.Request, m proto.Message) (bin bool, err error)
- func HttpReplyJson(w http.ResponseWriter, code int, obj any) error
- func HttpReplyJsonWithLog(logger *ContextLogger, w http.ResponseWriter, code int, obj any) error
- func HttpReplyPb(w http.ResponseWriter, code int, m proto.Message, bin bool) (err error)
- func IncrWithTTL(ctx context.Context, db *redis.Client, key string, ttlSeconds int64) (int64, error)
- func InitLog(path string, maxBackups, maxDays int)
- func IsMysqlDuplicateError(err error) bool
- func ListIntoSet[T comparable](list []T, set map[T]bool)
- func ListToSet[T comparable](list []T) map[T]bool
- func LoadJsonFile(filepath string, obj any) error
- func LoadYamlFile(filepath string, obj any) error
- func LogLevelEnabled(lv LogLevel) bool
- func MaybeMetrisName(name string) bool
- func NewCounter(name string) prometheus.Counter
- func NewCounterVec(name string, labelNames ...string) *prometheus.CounterVec
- func NewGauge(name string) prometheus.Gauge
- func NewGaugeVec(name string, labelNames ...string) *prometheus.GaugeVec
- func NewRedisClient(cfg *RedisConfig) *redis.Client
- func NewRedisClientWithCheck(cfg *RedisConfig) (*redis.Client, error)
- func NewRestfulRequest(ctx context.Context, method, url string, headers, params map[string]string, ...) (*http.Request, error)
- func NewSummary(name string) prometheus.Summary
- func NewSummaryVec(name string, labelNames ...string) *prometheus.SummaryVec
- func OverwriteMysqlParams(config string, patch map[string]string) string
- func RecordLatencyUs(s prometheus.Observer, begin time.Time)
- func ReplaceNilByDummy[T any](list []T) []T
- func RestfulDelete(ctx context.Context, url string, headers, params map[string]string) (code int, err error)
- func RestfulDo(ctx context.Context, method, url string, headers, params map[string]string, ...) (code int, err error)
- func RestfulGet(ctx context.Context, url string, headers, params map[string]string, out any) (code int, err error)
- func RestfulPatch(ctx context.Context, url string, headers, params map[string]string, obj any) (code int, err error)
- func RestfulPost(ctx context.Context, url string, headers, params map[string]string, ...) (code int, err error)
- func RestfulPut(ctx context.Context, url string, headers, params map[string]string, obj any) (code int, err error)
- func RunHttpServer(router http.Handler, address string) error
- func SetLogLevel(lv LogLevel)
- func SqlCreate(ctx context.Context, stmt *sql.Stmt, args ...any) (int64, error)
- func SqlModify(ctx context.Context, stmt *sql.Stmt, args ...any) (int64, error)
- func SyncLog()
- func TryRegisterMetris(r *prometheus.Registry, m prometheus.Collector)
- func TryToConvertMetrisName(name string) (string, error)
- func UnsafeBytesToString(b []byte) string
- func UnsafeStringToBytes(s string) []byte
- type ActionMetrics
- type ContextLogger
- func (l *ContextLogger) Debug(msg string)
- func (l *ContextLogger) Debugf(tpl string, args ...any)
- func (l *ContextLogger) Error(msg string)
- func (l *ContextLogger) Errorf(tpl string, args ...any)
- func (l *ContextLogger) Info(msg string)
- func (l *ContextLogger) Infof(tpl string, args ...any)
- func (l *ContextLogger) Warn(msg string)
- func (l *ContextLogger) Warnf(tpl string, args ...any)
- type LogLevel
- type RedisConfig
- type Xorshift
Constants ¶
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 GenRandomToken ¶
func GetRawLogger ¶
GetRawLogger returns the underlying zap.Logger instance.
func HandleRestfulResponse ¶
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 ¶
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 ¶
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 ¶
HttpReplyPb writes a protobuf message as either JSON or protobuf wire format.
func IncrWithTTL ¶
func InitLog ¶
InitLog initializes the global logger writing JSON logs to the given path. Repeated calls after initialization are ignored.
func IsMysqlDuplicateError ¶
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 ¶
LoadJsonFile reads a JSON file from filepath and decodes it into obj. obj must be a pointer to the target value.
func LoadYamlFile ¶
LoadYamlFile reads a YAML file from filepath and decodes it into obj. obj must be a pointer to the target value.
func LogLevelEnabled ¶
LogLevelEnabled reports whether the given level is enabled on the global logger.
func MaybeMetrisName ¶
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 ¶
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 ¶
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 TryRegisterMetris ¶
func TryRegisterMetris(r *prometheus.Registry, m prometheus.Collector)
TryRegisterMetris registers a collector and logs the error instead of failing.
func TryToConvertMetrisName ¶
TryToConvertMetrisName converts a string into a Prometheus metric name if possible.
func UnsafeBytesToString ¶
UnsafeBytesToString converts a byte slice to string without allocation. The returned string must not be used after b is modified.
func UnsafeStringToBytes ¶
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.