core

package module
v0.0.0-...-60e8322 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Accepted

func Accepted(w http.ResponseWriter, r *http.Request, data any)

func ContextMiddleware

func ContextMiddleware() func(http.Handler) http.Handler

ContextMiddleware adds common context values from headers

func Created

func Created(w http.ResponseWriter, r *http.Request, data any)

func Critical

func Critical(msg string, err error)

func Criticalf

func Criticalf(err error, format string, v ...interface{})

func Debug

func Debug(msg string)

func Debugf

func Debugf(format string, v ...interface{})

func Error

func Error(msg string)

func Errorf

func Errorf(format string, v ...interface{})

func Fatal

func Fatal(msg string)

func Fatalf

func Fatalf(format string, v ...interface{})

func GetOrgIDFromContext

func GetOrgIDFromContext(ctx context.Context) string

GetOrgIDFromContext extracts organization ID from context

func GetRequestIDFromContext

func GetRequestIDFromContext(ctx context.Context) string

GetRequestIDFromContext extracts request ID from context

func GetTraceIDFromContext

func GetTraceIDFromContext(ctx context.Context) string

GetTraceIDFromContext extracts trace ID from context

func GetUserIDFromContext

func GetUserIDFromContext(ctx context.Context) string

GetUserIDFromContext extracts user ID from context

func Info

func Info(msg string)

func Infof

func Infof(format string, v ...interface{})

func InitGlobalLogger

func InitGlobalLogger(cfg LogConfig)

InitGlobalLogger initializes global logger

func LoggingMiddleware

func LoggingMiddleware(logger *Logger) func(http.Handler) http.Handler

LoggingMiddleware only logs failed HTTP requests.

func NoContent

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

func OK

func OK(w http.ResponseWriter, r *http.Request, data any)

Common response helpers

func RecoveryMiddleware

func RecoveryMiddleware(logger *Logger) func(http.Handler) http.Handler

RecoveryMiddleware recovers from panics and logs them

func RespondError

func RespondError(w http.ResponseWriter, r *http.Request, err error)

RespondError handles error response - checks if error is AppError, otherwise returns 500

func Warn

func Warn(msg string)

func Warnf

func Warnf(format string, v ...interface{})

func WithOrgID

func WithOrgID(ctx context.Context, orgID string) context.Context

WithOrgID adds organization ID to context

func WithRequestID

func WithRequestID(ctx context.Context, requestID string) context.Context

WithRequestID adds request ID to context

func WithTraceID

func WithTraceID(ctx context.Context, traceID string) context.Context

WithTraceID adds trace ID to context (for distributed tracing)

func WithUserID

func WithUserID(ctx context.Context, userID string) context.Context

WithUserID adds user ID to context

func WriteAppError

func WriteAppError(w http.ResponseWriter, r *http.Request, err *AppError)

WriteAppError writes error response from AppError

func WriteError

func WriteError(w http.ResponseWriter, r *http.Request, status int, code, message string, details map[string]any)

WriteError writes error response

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, v any)

func WriteList

func WriteList(w http.ResponseWriter, r *http.Request, status int, data []any, page any)

WriteList writes success response with list data and pagination

func WriteSuccess

func WriteSuccess(w http.ResponseWriter, r *http.Request, status int, data any)

WriteSuccess writes success response with data

Types

type AppError

type AppError struct {
	HTTPStatus int            // HTTP status code
	Code       string         // Error code untuk client
	Message    string         // Human-readable message
	Details    map[string]any // Additional error details
	Err        error          // Underlying error (tidak di-expose ke client)
}

AppError represents application error with HTTP status code, error code, message, and details

func BadRequest

func BadRequest(message string) *AppError

Common error constructors

func Conflict

func Conflict(message string) *AppError

func Forbidden

func Forbidden(message string) *AppError

func InternalServerError

func InternalServerError(message string) *AppError

func IsAppError

func IsAppError(err error) (*AppError, bool)

IsAppError checks if error is AppError

func NewAppError

func NewAppError(httpStatus int, code, message string) *AppError

NewAppError creates a new application error

func NotFound

func NotFound(resource, id string) *AppError

func ServiceUnavailable

func ServiceUnavailable(message string) *AppError

func Unauthorized

func Unauthorized(message string) *AppError

func UnprocessableEntity

func UnprocessableEntity(message string) *AppError

func ValidationError

func ValidationError(err error) *AppError

ValidationError creates validation error from validator errors

func (*AppError) Error

func (e *AppError) Error() string

Error implements error interface

func (*AppError) Unwrap

func (e *AppError) Unwrap() error

Unwrap implements errors unwrapper

func (*AppError) WithDetail

func (e *AppError) WithDetail(key string, value any) *AppError

WithDetail adds a single detail to the error

func (*AppError) WithDetails

func (e *AppError) WithDetails(details map[string]any) *AppError

WithDetails adds details to the error

func (*AppError) WithError

func (e *AppError) WithError(err error) *AppError

WithError wraps underlying error

type ErrorBody

type ErrorBody struct {
	Code    string         `json:"code"`
	Message string         `json:"message"`
	Details map[string]any `json:"details,omitempty"`
}

type ErrorDetail

type ErrorDetail struct {
	Detail error `json:"-"`
}

func NewErrorDetail

func NewErrorDetail(err error) *ErrorDetail

func Wrap

func Wrap(err error) *ErrorDetail

func (*ErrorDetail) MarshalJSON

func (e *ErrorDetail) MarshalJSON() ([]byte, error)

type ErrorResponse

type ErrorResponse struct {
	Error ErrorBody `json:"error"`
	Meta  Meta      `json:"meta"`
}

type FieldErrors

type FieldErrors map[string]string

func ParseValidationErrors

func ParseValidationErrors(err error) FieldErrors

type List

type List struct {
	Data []any `json:"data"`
	Page any   `json:"page,omitempty"`
	Meta Meta  `json:"meta"`
}

type LogConfig

type LogConfig struct {
	Level         LogLevel // Log level
	ServiceName   string   // Service name (e.g., "control-plane-api")
	Environment   string   // Environment (e.g., "production", "staging", "development")
	Pretty        bool     // Pretty print for development
	Output        io.Writer
	ErrorOutput   io.Writer
	ErrorFilePath string
}

LogConfig holds logger configuration

type LogLevel

type LogLevel string

LogLevel represents log levels

const (
	LevelDebug LogLevel = "debug"
	LevelInfo  LogLevel = "info"
	LevelWarn  LogLevel = "warn"
	LevelError LogLevel = "error"
	LevelFatal LogLevel = "fatal"
)

type Logger

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

Logger wraps zerolog with additional functionality

func GetGlobalLogger

func GetGlobalLogger() *Logger

GetGlobalLogger returns global logger instance

func NewLogger

func NewLogger(cfg LogConfig) *Logger

NewLogger creates a new logger instance

func (*Logger) Critical

func (l *Logger) Critical(msg string, err error)

Critical logs critical error (for alerting) This should trigger alerts in Prometheus/Alertmanager

func (*Logger) Criticalf

func (l *Logger) Criticalf(err error, format string, v ...interface{})

Criticalf logs formatted critical error

func (*Logger) Debug

func (l *Logger) Debug(msg string)

Debug logs debug message

func (*Logger) Debugf

func (l *Logger) Debugf(format string, v ...interface{})

Debugf logs formatted debug message

func (*Logger) Error

func (l *Logger) Error(msg string)

Error logs error message

func (*Logger) Errorf

func (l *Logger) Errorf(format string, v ...interface{})

Errorf logs formatted error message

func (*Logger) Fatal

func (l *Logger) Fatal(msg string)

Fatal logs fatal message and exits

func (*Logger) Fatalf

func (l *Logger) Fatalf(format string, v ...interface{})

Fatalf logs formatted fatal message and exits

func (*Logger) Info

func (l *Logger) Info(msg string)

Info logs info message

func (*Logger) Infof

func (l *Logger) Infof(format string, v ...interface{})

Infof logs formatted info message

func (*Logger) LogAudit

func (l *Logger) LogAudit(actor, action, resource string, metadata map[string]interface{})

LogAudit logs audit events (security, compliance)

func (*Logger) LogDatabaseQuery

func (l *Logger) LogDatabaseQuery(query string, duration time.Duration, err error)

LogDatabaseQuery logs database queries (for debugging)

func (*Logger) LogHTTPRequest

func (l *Logger) LogHTTPRequest(method, path string, statusCode int, duration time.Duration, metadata map[string]interface{})

LogHTTPRequest logs HTTP requests

func (*Logger) LogMQEvent

func (l *Logger) LogMQEvent(eventType, topic string, success bool, metadata map[string]interface{})

LogMQEvent logs message queue events

func (*Logger) LogServiceState

func (l *Logger) LogServiceState(state, action string, metadata map[string]interface{})

LogServiceState logs service state changes

func (*Logger) Warn

func (l *Logger) Warn(msg string)

Warn logs warning message

func (*Logger) Warnf

func (l *Logger) Warnf(format string, v ...interface{})

Warnf logs formatted warning message

func (*Logger) WithContext

func (l *Logger) WithContext(ctx context.Context) *Logger

WithContext extracts logger from context or returns current logger

func (*Logger) WithError

func (l *Logger) WithError(err error) *Logger

WithError adds error to logger context

func (*Logger) WithField

func (l *Logger) WithField(key string, value interface{}) *Logger

WithField adds a single field to logger

func (*Logger) WithFields

func (l *Logger) WithFields(fields map[string]interface{}) *Logger

WithFields adds structured fields to logger

type Meta

type Meta struct {
	RequestID string    `json:"requestId"`
	Timestamp time.Time `json:"timestamp"`
}

type Success

type Success struct {
	Data any  `json:"data"`
	Meta Meta `json:"meta"`
}

Jump to

Keyboard shortcuts

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