csweb_utils

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2024 License: MIT Imports: 40 Imported by: 0

Documentation

Index

Constants

View Source
const AfterName = "gorm.after"
View Source
const BeforeName = "gorm.before"
View Source
const GormTrace = "gorm.trace"
View Source
const OneDayTimestamp = 86400

Variables

View Source
var (
	TokenExpired     = errors.New("expired token")
	TokenNotValidYet = errors.New("unactivated token")
	TokenMalformed   = errors.New("unknown token")
	TokenInvalid     = errors.New("invalid token")
)
View Source
var ClaimsKey struct{}
View Source
var PanicCounterMetrics = prometheus.NewCounter(prometheus.CounterOpts{
	Name: "grpc_req_panics_recovered_total",
	Help: "Total number of gRPC requests recovered from internal panic.",
})
View Source
var SrvMetrics = grpcprom.NewServerMetrics(
	grpcprom.WithServerHandlingTimeHistogram(
		grpcprom.WithHistogramBuckets([]float64{0.001, 0.01, 0.1, 0.3, 0.6, 1, 3, 6, 9, 20, 30, 60, 90, 120}),
	),
)

Functions

func ArgumentError

func ArgumentError(format string, a ...any) error

func CheckQueryPaging added in v0.0.3

func CheckQueryPaging(paging *common.Page, defaultPageSize int32) *common.Page

func CommitFence

func CommitFence(ctx context.Context, db *gorm.DB, confirm func(ctx context.Context, tx *gorm.DB) (ok bool, err error)) (ok bool, err error)

func CookieToAuth

func CookieToAuth(cookieKey string) func(ctx context.Context, req *http.Request) metadata.MD

CookieToAuth Specifies that the value of the cookie key is converted to the value of the header Authorization

func CurrentDB

func CurrentDB(ctx context.Context, db *gorm.DB) *gorm.DB

CurrentDB 如果context里面有事务连接则使用事务连接,否则使用db

func CustomErrorHandler

func CustomErrorHandler(ctx context.Context, mux *runtime.ServeMux, marshaler runtime.Marshaler, writer http.ResponseWriter, request *http.Request, err error)

CustomErrorHandler custom Error Handler for HTTP Server

func DeleteError

func DeleteError(obj string) error

func GetFilterTime added in v0.0.3

func GetFilterTime(start, end string) (startTime, endTime string, err error)

func GetResultPaging added in v0.0.3

func GetResultPaging(query *common.Page, totalCount int32) (result *common.Page)

func GetTraceId

func GetTraceId(ctx context.Context) string

GetTraceId get traceId from context

func GetTxLogObj

func GetTxLogObj(ctx context.Context, txLogObj interface{}) (err error)

func GetUserName

func GetUserName(ctx context.Context) string

func GetXidFromContext

func GetXidFromContext(ctx context.Context) string

func InitMetrics

func InitMetrics()

func InitTracerProvider

func InitTracerProvider(name, addr string) error

InitTracerProvider init tracer Provider

func InterceptorLogger

func InterceptorLogger(l logrus.FieldLogger) logging.Logger

InterceptorLogger adapts logrus logger to interceptor logger.

func InternalError

func InternalError(format string, a ...any) error

func LogWithContext

func LogWithContext(ctx context.Context) *logrus.Entry

LogWithContext get logger with fields(traceId,spanId)

func NewGormDB

func NewGormDB(dsn string) (*gorm.DB, error)

NewGormDB 初始化DB

func NewORMOptsContext

func NewORMOptsContext(ctx context.Context, opts ...ORMOption) context.Context

func NewTxContext

func NewTxContext(ctx context.Context, db *gorm.DB) context.Context

NewTxContext ctx传递事务连接

func NotFoundError

func NotFoundError(err error) error

func NotTxContext

func NotTxContext(ctx context.Context) context.Context

NotTxContext context清理事务DB

func OK

func OK(ctx context.Context) *common.Status

func PermissionDeniedError

func PermissionDeniedError() error

func PrepareFence

func PrepareFence(ctx context.Context, db *gorm.DB, prepare func(ctx context.Context, tx *gorm.DB) (txLogObj interface{}, ok bool, err error)) (ok bool, err error)

func QueryError

func QueryError(obj string) error

func RespOK

func RespOK(ctx context.Context) *common.Response

func RollbackFence

func RollbackFence(ctx context.Context, db *gorm.DB, cancel func(ctx context.Context, tx *gorm.DB) (ok bool, err error)) (ok bool, err error)

func SetClaimsWithContext

func SetClaimsWithContext(ctx context.Context, claims *CustomClaims) context.Context

func TxFromContext

func TxFromContext(ctx context.Context) *gorm.DB

TxFromContext 从ctx获取事务连接

func UpdateError

func UpdateError(obj string) error

func WithJwtAuth

func WithJwtAuth(signKey string, filterMethods ...string) grpc.UnaryServerInterceptor

func WithLogger

func WithLogger() grpc.UnaryServerInterceptor

func WithMetrics

func WithMetrics() grpc.UnaryServerInterceptor

func WithRateLimit

func WithRateLimit(num int) grpc.UnaryServerInterceptor

WithRateLimit return a new unary server interceptors that performs request rate limiting.

func WithRecovery

func WithRecovery() grpc.UnaryServerInterceptor

func WithTrace

func WithTrace(h http.Handler) http.Handler

WithTrace inject traceId for customErrorHandler

func WithValidator

func WithValidator() grpc.UnaryServerInterceptor

Types

type CustomClaims

type CustomClaims struct {
	UID         string
	Username    string
	NickName    string
	AuthorityId string
	jwt.StandardClaims
}

func GetClaims

func GetClaims(ctx context.Context) *CustomClaims

type ErrResp

type ErrResp struct {
	Status Status `json:"status"`
}

type GormTracer

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

GormTracer gorm trace追踪

func NewGormTracer

func NewGormTracer(db *gorm.DB, spanName string) *GormTracer

func (*GormTracer) Init

func (g *GormTracer) Init() error

type JWT

type JWT struct {
	SigningKey []byte
}

func NewJWT

func NewJWT(signKey string) *JWT

func (*JWT) CreateToken

func (j *JWT) CreateToken(claims CustomClaims) (string, error)

CreateToken 创建一个token

func (*JWT) ParseToken

func (j *JWT) ParseToken(tokenString string) (*CustomClaims, error)

ParseToken 解析 token

type ORMOption

type ORMOption func(db *gorm.DB) *gorm.DB

func ORMOptsFromContext

func ORMOptsFromContext(ctx context.Context) []ORMOption

ORMOptsFromContext 获取orm的options

type Status

type Status struct {
	TraceId string `json:"traceId"`
	Code    int32  `json:"code"`
	Message string `json:"message"`
}

type TokenBucket

type TokenBucket struct {
	Num        int           // 当前桶中的令牌数据
	Size       int           // 木桶中令牌的容量
	Rate       time.Duration // 生成一个令牌所需要的时间
	UpdateTime time.Time     // 记录每次令牌桶更新时间
}

TokenBucket 令牌桶结构体

func NewTokenBucket

func NewTokenBucket(size int, rate time.Duration) *TokenBucket

NewTokenBucket 创建令牌桶

func (*TokenBucket) Limit

func (that *TokenBucket) Limit(_ context.Context) bool

Limit 验证是否能获取一个令牌

type TxLog

type TxLog struct {
	Xid        string
	BranchId   string
	ActionName string
	LogDetail  []byte
	TxLogState TxLogState
	*gorm.Model
}

type TxLogState

type TxLogState int8
const (
	TxLogStateInit TxLogState = iota
	TxLogStateCommit
	TxLogStateRollback
)

Jump to

Keyboard shortcuts

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