Documentation ¶
Index ¶
- Constants
- Variables
- func AccessorGetOne[T any](ctx context.Context, accessor *DbAccessor, proto *T) (*T, error)
- func AccessorGetOneByKey[T any](ctx context.Context, accessor *DbAccessor, key interface{}) (*T, error)
- func AccessorQueryAll[T any](ctx context.Context, accessor *DbAccessor, sql string, mapper RowMapper, ...) ([]*T, error)
- func AccessorQueryOne[T any](ctx context.Context, accessor *DbAccessor, sql string, mapper RowMapper, ...) (*T, error)
- func Aes256Decrypt(key, iv, data []byte) ([]byte, error)
- func Aes256Encrypt(key, iv, data []byte) ([]byte, error)
- func CalculateMd5PartitionKey(key string) int32
- func CalculateMd5PartitionKey2(key string) int32
- func ClusterGetAll[T any](ctx context.Context, cluster *MyCluster, query string, args ...interface{}) ([][]*T, error)
- func ClusterGetOne[T any](ctx context.Context, cluster *MyCluster, query string, ...) (*T, error)
- func ClusterGetPage[T any](ctx context.Context, cluster *MyCluster, query string, merger *PageMerger[any], ...) ([]*T, error)
- func ClusterQueryAll[T any](ctx context.Context, cluster *MyCluster, query string, mapper RowMapper, ...) ([][]*T, error)
- func ClusterQueryOne[T any](ctx context.Context, cluster *MyCluster, query string, mapper RowMapper, ...) (*T, error)
- func ClusterQueryPage[T any](ctx context.Context, cluster *MyCluster, query string, mapper RowMapper, ...) ([]*T, error)
- func ConvertToEpochMillis(t time.Time) int64
- func DecodeRsaPrivateKey(payload []byte) (*rsa.PrivateKey, error)
- func DecodeRsaPublicKey(payload []byte) (*rsa.PublicKey, error)
- func GetEpochMillis() int64
- func GetFieldValueGetters(t reflect.Type) map[string]*FieldValueGetter
- func GetPartitionKey(id int64) int32
- func GetTraceID(ctx context.Context) string
- func LoadRsaPrivateKey(pemFile string) (*rsa.PrivateKey, error)
- func LoadRsaPublicKey(pemFile string) (*rsa.PublicKey, error)
- func LogExec(activityID string, start time.Time, err error)
- func LogOperation(ctx context.Context, operation string, operator func() error) error
- func LoggingHandler(handler http.Handler) http.Handler
- func Max[T Ordered](v1, v2 T) T
- func Md5(data []byte) []byte
- func Min[T Ordered](v1, v2 T) T
- func NewRollingLogWriter(fileName string, maxSizeInMegaBytes, maxRotationFiles int) io.Writer
- func NewSessionHandler(pipeline http.Handler, store SessionStore, timeout time.Duration, ...) http.Handler
- func NewSessionID() string
- func OrderedCompare[T Ordered](lh T, rh T) int
- func QueryAll(ctx context.Context, queryable Queryable, mapper RowMapper, query string, ...) ([]interface{}, error)
- func QueryAllEntities[TEntity any](ctx context.Context, queryable Queryable, mapper RowMapper, query string, ...) ([]*TEntity, error)
- func QueryAllWithCollector(ctx context.Context, queryable Queryable, mapper RowMapper, query string, ...) error
- func QueryOne(ctx context.Context, queryable Queryable, mapper RowMapper, query string, ...) (interface{}, error)
- func QueryOneEntity[TEntity any](ctx context.Context, queryable Queryable, mapper RowMapper, query string, ...) (*TEntity, error)
- func SendError(writer http.ResponseWriter, statusCode int, errorMsg string)
- func SetupLogger(level LogLevel, writer io.Writer)
- func Sha1(data []byte) []byte
- func Sha256(data []byte) []byte
- func ToSnakeCase(str string) string
- func TxnGetOne[T any](txn Txn, proto *T) (*T, error)
- func TxnGetOneByKey[T any](txn Txn, key interface{}) (*T, error)
- func TxnQueryAll[T any](txn Txn, sql string, mapper RowMapper, args ...interface{}) ([]*T, error)
- func TxnQueryOne[T any](txn Txn, sql string, mapper RowMapper, args ...interface{}) (*T, error)
- type Action
- type ActionHandler
- type AuthorizationManager
- type BufferedWriter
- type ClusterTxn
- type CollectorCreatorFunc
- type CompareFunc
- type Comparer
- type Complex
- type ConcurrentMap
- func (m *ConcurrentMap[TKey, TValue]) Delete(key TKey)
- func (m *ConcurrentMap[TKey, TValue]) Foreach(f func(key TKey, value TValue))
- func (m *ConcurrentMap[TKey, TValue]) Get(key TKey) (TValue, bool)
- func (m *ConcurrentMap[TKey, TValue]) GetOrCompute(key TKey, generator func() TValue) TValue
- func (m *ConcurrentMap[TKey, TValue]) Len() int
- func (m *ConcurrentMap[TKey, TValue]) Put(key TKey, value TValue) (TValue, bool)
- func (m *ConcurrentMap[TKey, TValue]) RemoveIf(evaluator func(key TKey, value TValue) bool) int
- type Controller
- type ControllerFunc
- type CustomHandler
- type CustomHandlerFunc
- type DataCollector
- type DataCollectorCreator
- type DataCollectorFunc
- type DataPage
- type DataRow
- type DbAccessor
- func (accessor *DbAccessor) BeginTxn(ctx context.Context) (*DbTxn, error)
- func (accessor *DbAccessor) BeginTxnWithIsolation(ctx context.Context, isolation sql.IsolationLevel) (*DbTxn, error)
- func (accessor *DbAccessor) Conn(ctx context.Context) (*sql.Conn, error)
- func (accessor *DbAccessor) Delete(ctx context.Context, entity interface{}) (sql.Result, error)
- func (accessor *DbAccessor) Execute(ctx context.Context, command string, args ...interface{}) (sql.Result, error)
- func (accessor *DbAccessor) GetOne(ctx context.Context, proto interface{}) (interface{}, error)
- func (accessor *DbAccessor) GetOneByKey(ctx context.Context, ty reflect.Type, key interface{}) (interface{}, error)
- func (accessor *DbAccessor) Insert(ctx context.Context, entity interface{}) (sql.Result, error)
- func (accessor *DbAccessor) QueryAll(ctx context.Context, query string, mapper RowMapper, args ...interface{}) ([]interface{}, error)
- func (accessor *DbAccessor) QueryAllWithCollector(ctx context.Context, query string, mapper RowMapper, collector DataCollector, ...) error
- func (accessor *DbAccessor) QueryOne(ctx context.Context, query string, mapper RowMapper, args ...interface{}) (interface{}, error)
- func (accessor *DbAccessor) Update(ctx context.Context, entity interface{}) (sql.Result, error)
- type DbClusterTxnStore
- func (store *DbClusterTxnStore) AddTxnParticipant(ctx context.Context, txnID string, partition int) error
- func (store *DbClusterTxnStore) Close() error
- func (store *DbClusterTxnStore) CreateTxn(ctx context.Context, txnID string, t time.Time) (*ClusterTxn, error)
- func (store *DbClusterTxnStore) DeleteTxn(ctx context.Context, txnID string) error
- func (store *DbClusterTxnStore) GetTxn(ctx context.Context, txnID string) (*ClusterTxn, error)
- func (store *DbClusterTxnStore) LeaseExpiredTxns(ctx context.Context, expireTime, leaseTimeout time.Time, items int) ([]*ClusterTxn, error)
- func (store *DbClusterTxnStore) ListParticipants(ctx context.Context, txnID string) ([]*TxnParticipant, error)
- func (store *DbClusterTxnStore) UpdateTxnState(ctx context.Context, txnID string, state int) error
- type DbTxn
- func (txn *DbTxn) Close()
- func (txn *DbTxn) Commit() error
- func (txn *DbTxn) Delete(entity interface{}) (sql.Result, error)
- func (txn *DbTxn) Execute(command string, args ...interface{}) (sql.Result, error)
- func (txn *DbTxn) GetOne(proto interface{}) (interface{}, error)
- func (txn *DbTxn) GetOneByKey(ty reflect.Type, key interface{}) (interface{}, error)
- func (txn *DbTxn) Insert(entity interface{}) (sql.Result, error)
- func (txn *DbTxn) QueryAll(query string, mapper RowMapper, args ...interface{}) ([]interface{}, error)
- func (txn *DbTxn) QueryAllWithCollector(query string, mapper RowMapper, collector DataCollector, args ...interface{}) error
- func (txn *DbTxn) QueryOne(query string, mapper RowMapper, args ...interface{}) (interface{}, error)
- func (txn *DbTxn) Rollback() error
- func (txn *DbTxn) Update(entity interface{}) (sql.Result, error)
- type DbUniqueIDGenerator
- type DistributedLocker
- type DistributedSharedLocker
- type DummyWriter
- type EntityDescriptor
- type FieldValueGetter
- type Float
- type Integer
- type JwtKeyMap
- type JwtKeyProvider
- type JwtUserClaims
- type JwtUserPrincipal
- type JwtUserProvider
- type KeepAliveMessageHandler
- type LockContext
- type LogLevel
- type MyCluster
- func (cluster *MyCluster) Close()
- func (cluster *MyCluster) CreateTransaction(ctx context.Context) (*MyClusterTxn, error)
- func (cluster *MyCluster) Delete(ctx context.Context, entity interface{}) (sql.Result, error)
- func (cluster *MyCluster) ExecuteOnAll(ctx context.Context, query string, args ...interface{}) error
- func (cluster *MyCluster) GenerateKey(ctx context.Context, entity interface{}) error
- func (cluster *MyCluster) GetAll(ctx context.Context, ty reflect.Type, query string, args ...interface{}) ([][]interface{}, error)
- func (cluster *MyCluster) GetAllPartitions() []*DbAccessor
- func (cluster *MyCluster) GetAllReduced(ctx context.Context, ty reflect.Type, query string, ...) ([]interface{}, error)
- func (cluster *MyCluster) GetAllWithCollector(ctx context.Context, ty reflect.Type, query string, ...) error
- func (cluster *MyCluster) GetAnyPartition() *DbAccessor
- func (cluster *MyCluster) GetDbAccessor(partition int32) *DbAccessor
- func (cluster *MyCluster) GetDbAccessorByID(id int64) *DbAccessor
- func (cluster *MyCluster) GetDbAccessorByKey(partitionKey string) *DbAccessor
- func (cluster *MyCluster) GetOne(ctx context.Context, ty reflect.Type, query string, ...) (interface{}, error)
- func (cluster *MyCluster) GetPage(ctx context.Context, ty reflect.Type, query string, merger *PageMerger[any], ...) ([]interface{}, error)
- func (cluster *MyCluster) GetPartitionByKey(key string) int32
- func (cluster *MyCluster) GetUniqueID(ctx context.Context, entity interface{}, partition int32) (int64, error)
- func (cluster *MyCluster) GetUniqueIDByName(ctx context.Context, entityName string, partition int32) (int64, error)
- func (cluster *MyCluster) Insert(ctx context.Context, entity interface{}) error
- func (cluster *MyCluster) InsertAt(ctx context.Context, partition int32, entity interface{}) error
- func (cluster *MyCluster) InsertByKey(ctx context.Context, partitionKey string, entity interface{}) error
- func (cluster *MyCluster) InsertToAll(ctx context.Context, entity interface{}) error
- func (cluster *MyCluster) QueryAll(ctx context.Context, query string, mapper RowMapper, args ...interface{}) ([][]interface{}, error)
- func (cluster *MyCluster) QueryAllReduced(ctx context.Context, query string, mapper RowMapper, ...) ([]interface{}, error)
- func (cluster *MyCluster) QueryAllWithCollector(ctx context.Context, query string, mapper RowMapper, ...) error
- func (cluster *MyCluster) QueryOne(ctx context.Context, query string, mapper RowMapper, ...) (interface{}, error)
- func (cluster *MyCluster) QueryPage(ctx context.Context, query string, mapper RowMapper, merger *PageMerger[any], ...) ([]interface{}, error)
- func (cluster *MyCluster) Update(ctx context.Context, entity interface{}) error
- func (cluster *MyCluster) UpdateAt(ctx context.Context, partition int32, entity interface{}) error
- func (cluster *MyCluster) UpdateToAll(ctx context.Context, entity interface{}) error
- type MyClusterTxn
- func (txn *MyClusterTxn) Close()
- func (txn *MyClusterTxn) Commit() error
- func (txn *MyClusterTxn) Delete(entity interface{}) (sql.Result, error)
- func (txn *MyClusterTxn) DeleteAt(partition int32, entity interface{}) (sql.Result, error)
- func (txn *MyClusterTxn) DeleteFromAll(entity interface{}) ([]sql.Result, error)
- func (txn *MyClusterTxn) ExecuteAt(partition int32, sql string, args ...interface{}) (sql.Result, error)
- func (txn *MyClusterTxn) ExecuteOnAll(query string, args ...interface{}) ([]sql.Result, error)
- func (txn *MyClusterTxn) GetTxnByID(id int64) (*XATransaction, error)
- func (txn *MyClusterTxn) GetTxnByPartition(partition int32) (*XATransaction, error)
- func (txn *MyClusterTxn) InsertAt(partition int32, entity interface{}) (sql.Result, error)
- func (txn *MyClusterTxn) InsertToAll(entity interface{}) ([]sql.Result, error)
- func (txn *MyClusterTxn) Rollback() error
- func (txn *MyClusterTxn) Update(entity interface{}) (sql.Result, error)
- func (txn *MyClusterTxn) UpdateAt(partition int32, entity interface{}) (sql.Result, error)
- func (txn *MyClusterTxn) UpdateToAll(entity interface{}) ([]sql.Result, error)
- type Ordered
- type PageMerger
- type PageQuery
- func (q *PageQuery[T, TPrimaryKey, TSecondaryKey]) DoQuery(ctx context.Context, paging, pageToken string, pageSize int) (*DataPage[*T], error)
- func (q *PageQuery[T, TPrimaryKey, TSecondaryKey]) DoQueryWithCustomPageToken(ctx context.Context, paging, pagingToken string, pageSize int, ...) (*DataPage[*T], error)
- type PartitionCalculateFunc
- type PartitionCalculator
- type PooledID
- type Queryable
- type Response
- func (r *Response) DoneWithContent(statusCode int, contentType string, content []byte)
- func (r *Response) DoneWithError(statusCode int, msg string)
- func (r *Response) DoneWithJSON(statusCode int, obj interface{})
- func (r *Response) DoneWithRedirect(req *http.Request, url string, status int)
- func (r *Response) DoneWithTemplate(statusCode int, name string, model interface{})
- func (r *Response) SetCookie(cookie *http.Cookie)
- func (r *Response) SetHeader(name, value string)
- func (r *Response) SetNoCache()
- func (r *Response) SetStatus(statusCode int)
- func (r *Response) Write(content []byte) (int, error)
- type RowMapper
- type RowMapperFunc
- type SecurityHandler
- func (handler *SecurityHandler) AddUserProvider(userProvider UserProvider) *SecurityHandler
- func (handler *SecurityHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request)
- func (handler *SecurityHandler) WithAuthz(authz AuthorizationManager) *SecurityHandler
- func (handler *SecurityHandler) WithLoginURL(loginURL string) *SecurityHandler
- func (handler *SecurityHandler) WithPipeline(h http.Handler) *SecurityHandler
- type Session
- func (session *Session) Deserialize(data []byte)
- func (session *Session) GetAsFlashValue(key string) (interface{}, bool)
- func (session *Session) GetValue(key string) (interface{}, bool)
- func (session *Session) NeedSave() bool
- func (session *Session) Serialize() []byte
- func (session *Session) SetValue(key string, value interface{}) (interface{}, bool)
- type SessionStore
- type SharedTemplateDetector
- type Signed
- type SkinManager
- func (skinMgr *SkinManager) AddSkin(name string, tmplMgr *TemplateManager)
- func (skinMgr *SkinManager) ApplySelector(request *http.Request) (*TemplateManager, string)
- func (skinMgr *SkinManager) GetDefaultSkin() *TemplateManager
- func (skinMgr *SkinManager) GetSkin(name string) (*TemplateManager, bool)
- func (skinMgr *SkinManager) GetSkinOrDefault(name string) *TemplateManager
- func (skinMgr *SkinManager) RemoveSkin(name string)
- func (skinMgr *SkinManager) WithSelector(selector SkinSelector)
- type SkinSelector
- type SkinSelectorFunc
- type SliceCollector
- type SliceCollectorCreator
- type Stringify
- type TableNameResolver
- type TableNameResolverFunc
- type TemplateConfigFunc
- type TemplateManager
- type Txn
- type TxnParticipant
- type TxnStore
- type UniqueID
- type UniqueIDGenerator
- type UniqueIDPool
- type Unsigned
- type UserPrincipal
- type UserPrincipalLoader
- type UserPrincipalLoaderFunc
- type UserProvider
- type WebServer
- func (server *WebServer) AddStaticResource(prefix, dir string) *WebServer
- func (server *WebServer) AddUserProvider(provider UserProvider) *WebServer
- func (server *WebServer) AddWsEndoint(endpoint string, listener WebSocketListener) *WebServer
- func (server *WebServer) AddWsHandler(endpoint string, handler *WebSocketHandler) *WebServer
- func (server *WebServer) HandleFunc(path string, f func(w http.ResponseWriter, r *http.Request)) *WebServer
- func (server *WebServer) RegisterController(name string, controller Controller) error
- func (server *WebServer) Shutdown()
- func (server *WebServer) Start() error
- func (server *WebServer) WithAuthz(authz AuthorizationManager) *WebServer
- func (server *WebServer) WithCORS(handler func(http.Handler) http.Handler) *WebServer
- func (server *WebServer) WithCaptcha(path string) *WebServer
- func (server *WebServer) WithCaptchaCustom(path string, digits, width, height int) *WebServer
- func (server *WebServer) WithCustomHandler(handler CustomHandler) *WebServer
- func (server *WebServer) WithLoginURL(loginURL string) *WebServer
- func (server *WebServer) WithRequestTimeout(timeout int)
- func (server *WebServer) WithSessionOptions(store SessionStore, timeout time.Duration, valueTypes ...interface{}) *WebServer
- func (server *WebServer) WithStandardRouting(prefix string) *WebServer
- type WebSocketHandler
- type WebSocketListener
- type WebSocketSession
- type XATransaction
- func (xa *XATransaction) Begin() error
- func (xa *XATransaction) Close()
- func (xa *XATransaction) Delete(entity interface{}) (sql.Result, error)
- func (xa *XATransaction) Execute(command string, args ...interface{}) (sql.Result, error)
- func (xa *XATransaction) GetOne(proto interface{}) (interface{}, error)
- func (xa *XATransaction) GetOneByKey(ty reflect.Type, key interface{}) (interface{}, error)
- func (xa *XATransaction) Insert(entity interface{}) (sql.Result, error)
- func (xa *XATransaction) QueryAll(query string, mapper RowMapper, args ...interface{}) ([]interface{}, error)
- func (xa *XATransaction) QueryAllWithCollector(query string, mapper RowMapper, collector DataCollector, args ...interface{}) error
- func (xa *XATransaction) QueryOne(query string, mapper RowMapper, args ...interface{}) (interface{}, error)
- func (xa *XATransaction) Update(entity interface{}) (sql.Result, error)
- type XaTxnID
- type ZkLock
- type ZkLock2
- type ZkRWLock
- type ZkRWLock2
Constants ¶
const ( // ClusterTxnStateNone nil state ClusterTxnStateNone = iota // ClusterTxnStateCommitted state committed ClusterTxnStateCommitted // ClusterTxnStateRollback state rollback ClusterTxnStateRollback )
const ( // XAStateUnknown state unknown XAStateUnknown = iota // XAStateActive state active XAStateActive // XAStateIdle state idle XAStateIdle // XAStatePrepared state prepared XAStatePrepared // XAStateRollback state rollback XAStateRollback // XAStateCommitted state committed XAStateCommitted )
const ( // EntityTagsDTags dtags tag EntityTagsDTags = "dtags" // EntityTagsDTagsKey key flag in dtags EntityTagsDTagsKey = "key" // EntityTagsDTagsSecure secure flag in dtags EntityTagsDTagsSecure = "secure" // EntityTagsDTagsNoUpdate noupdate flag in dtags EntityTagsDTagsNoUpdate = "noupdate" // EntityTagsDTagsNoGen nogen flag in dtags EntityTagsDTagsNoGen = "nogen" // EntityTagsDTagsMultiKey multikey flag in dtags EntityTagsDTagsMultiKey = "multikey" // EntityTagsDTagsAutoInc autoinc flag in dtags EntityTagsDTagsAutoInc = "autoinc" // EntityTagsDTagsPartition partition flag in dtags EntityTagsDTagsPartition = "partition" // EntityTagsCol col tag EntityTagsCol = "col" // EntityTagsAlias alias tag EntityTagsAlias = "alias" // EntityTagsPrefix prefix tag EntityTagsPrefix = "prefix" PagingNext = "next" PagingPrev = "prev" PagingNone = "none" )
const ( TraceActivityIDKey = "TraceActivityID" UserPrincipalKey = "UserPrincipal" SessionKey = "UserSession" )
Context keys
const ( DefaultJwtProviderName = "JWT" BackupKeyNameSuffix = "$backup" )
const ( // PartitionKeyBitWidth bits for partition value PartitionKeyBitWidth = 5 // PartitionKeyMask partition value mask PartitionKeyMask = 0x1f // SegmentedIDBitWidth segmented id value bit width SegmentedIDBitWidth = 7 // SegmentedIDMask segmented id value mask SegmentedIDMask = 0x7f // PooledIDBitWidth pooled id value bit width PooledIDBitWidth = PartitionKeyBitWidth + SegmentedIDBitWidth // MaxPooledID maximum pooled id MaxPooledID = (int64(1) << (64 - PooledIDBitWidth)) - 1 // MaxSegmentedID max segmented id MaxSegmentedID = int64(1 << SegmentedIDBitWidth) )
Variables ¶
var ( //EntityToTableNameMapper entity name to table name mapper EntityToTableNameMapper = TableNameResolverFunc(ToSnakeCase) // SQLIdentifierQuoteLeft sql identifier quote left SQLIdentifierQuoteLeft = "`" // SQLIdentifierQuoteRight sql identifier quote right SQLIdentifierQuoteRight = "`" )
var ( // ErrDirectoryRequired a directory is expected but file is seen ErrDirectoryRequired = errors.New("a directory is required") // ErrFileRequired a file is expected but directory is seen ErrFileRequired = errors.New("a file is required") // ErrBadSessionFile failed to read session data from session file ErrBadSessionFile = errors.New("bad session file") )
var ( //ErrNoFile no file given for Creating a template ErrNoFile = errors.New("no template file") //SkinDefault default skin name SkinDefault = "default" )
var ( // ErrDupActionName mulitple actions are having the same name for the same controller ErrDupActionName = errors.New("action name duplicated") // ServerName name of the app ServerName = "cypress" // ServerVersion version of the server ServerVersion = "v0.1.1110" // CaptchaKey captcha key in session CaptchaKey = "captcha" // CaptchaSessionKey captcha alternative session key parameter name CaptchaSessionKey = "sessid" // NotFoundMsg message to be shown when resource not found NotFoundMsg = "Sorry, we are not able to find the resource you requested" )
var ( // ErrLockFailed failed to lock ErrLockFailed = errors.New("failed to lock") // ErrLockCancelled not able to acquire the lock before context has cancelled ErrLockCancelled = errors.New("context cancelled before lock is acquired") )
var ( // CorrelationIDHeader http header name for correlation id header CorrelationIDHeader = http.CanonicalHeaderKey("x-correlation-id") )
var ( // ErrOutOfRange value out of range ErrOutOfRange = errors.New("value out of range") )
var ( // ErrPointerRequired a pointer is required ErrPointerRequired = errors.New("a pointer is required") )
var ( // ErrSessionNotFound a session with the specified key cannot be found ErrSessionNotFound = errors.New("session not found") )
var (
ZkLock2MaxConcurrentThreads int64 = int64(math.MaxInt32) / 2
)
Functions ¶
func AccessorGetOne ¶
func AccessorGetOne[T any](ctx context.Context, accessor *DbAccessor, proto *T) (*T, error)
func AccessorGetOneByKey ¶
func AccessorGetOneByKey[T any](ctx context.Context, accessor *DbAccessor, key interface{}) (*T, error)
func AccessorQueryAll ¶
func AccessorQueryOne ¶
func Aes256Decrypt ¶
Aes256Decrypt decrypts the data with given key and iv using AES256/CBC/PKCS5Padding
func Aes256Encrypt ¶
Aes256Encrypt encrypts the data with given key and iv using AES256/CBC/PKCS5Padding
func CalculateMd5PartitionKey ¶
CalculateMd5PartitionKey Md5 based partition key calculator
func CalculateMd5PartitionKey2 ¶
CalculateMd5PartitionKey2 Md5 based partition key calculator, a fixed version to CalculateMd5PartitionKey
func ClusterGetAll ¶
func ClusterGetOne ¶
func ClusterGetPage ¶
func ClusterQueryAll ¶
func ClusterQueryOne ¶
func ClusterQueryPage ¶
func ConvertToEpochMillis ¶
ConvertToEpochMillis convert a time object to epoch in milliseconds
func DecodeRsaPrivateKey ¶
func DecodeRsaPrivateKey(payload []byte) (*rsa.PrivateKey, error)
DecodeRsaPrivateKey decode rsa private key from pem payload
func DecodeRsaPublicKey ¶
DecodeRsaPublicKey decodes rsa public key from pem payload
func GetFieldValueGetters ¶
func GetFieldValueGetters(t reflect.Type) map[string]*FieldValueGetter
GetFieldValueGetters gets all possible FieldValueGetters for the give type t
func GetPartitionKey ¶
GetPartitionKey gets the partition key from the given unique ID value
func GetTraceID ¶
GetTraceID get the trace ID related to the context
func LoadRsaPrivateKey ¶
func LoadRsaPrivateKey(pemFile string) (*rsa.PrivateKey, error)
LoadRsaPrivateKey load rsa private key from pem file
func LoadRsaPublicKey ¶
LoadRsaPublicKey load rsa public key from pem file
func LogOperation ¶
LogOperation emit latency and error (if any) for the given operation
func LoggingHandler ¶
LoggingHandler http incoming logging handler
func NewRollingLogWriter ¶
NewRollingLogWriter returns a new file based rolling log writer maxSizeInMegaBytes specifies the maximum size of each log file, while maxRotationFiles tells the maximum files to keep
func NewSessionHandler ¶
func NewSessionHandler(pipeline http.Handler, store SessionStore, timeout time.Duration, valueTypes ...interface{}) http.Handler
NewSessionHandler creates a new session handler with registering the session object types
func OrderedCompare ¶ added in v1.4.9
func QueryAll ¶
func QueryAll(ctx context.Context, queryable Queryable, mapper RowMapper, query string, args ...interface{}) ([]interface{}, error)
QueryAll query all rows and map them to objects
func QueryAllEntities ¶
func QueryAllWithCollector ¶
func QueryOne ¶
func QueryOne(ctx context.Context, queryable Queryable, mapper RowMapper, query string, args ...interface{}) (interface{}, error)
QueryOne query one object
func QueryOneEntity ¶
func SendError ¶
func SendError(writer http.ResponseWriter, statusCode int, errorMsg string)
SendError complete the request by sending an error message to the client
func SetupLogger ¶
SetupLogger setup the global logger with specified log writer and log level this must be called before the logging can actually work
func TxnGetOneByKey ¶
func TxnQueryAll ¶
Types ¶
type ActionHandler ¶
ActionHandler action handler for standard routing
type AuthorizationManager ¶
type AuthorizationManager interface { // CheckAccess check the user to see if the user has permission to access // path with the given http method CheckAccess(user *UserPrincipal, method, path string) bool // CheckAnonymousAccessible checks the given path can be accessed by anonymous // user with the given http method CheckAnonymousAccessible(method, path string) bool }
AuthorizationManager an interface used by the security handler to check if the given user has permission to use the specified method and access the given path
type BufferedWriter ¶
type BufferedWriter struct {
Buffer [][]byte
}
BufferedWriter writes everything into memory
func NewBufferWriter ¶
func NewBufferWriter() *BufferedWriter
NewBufferWriter creates a new buffer based writer
type ClusterTxn ¶
type ClusterTxn struct { ID string `col:"id" dtags:"key,nogen"` State int `col:"state"` Timestamp int64 `col:"timestamp"` LeaseExpiration int64 `col:"lease_expiration"` }
ClusterTxn cluster transaction entity
type CollectorCreatorFunc ¶
type CollectorCreatorFunc func() DataCollector
func (CollectorCreatorFunc) Create ¶
func (creator CollectorCreatorFunc) Create() DataCollector
type CompareFunc ¶
CompareFunc function implements Comparer
func (CompareFunc[T]) Compare ¶
func (f CompareFunc[T]) Compare(lh T, rh T) int
Compare implements Comparer
type Complex ¶ added in v1.4.9
type Complex interface { ~complex64 | ~complex128 }
Complex is a constraint that permits any complex numeric type. If future releases of Go add new predeclared complex numeric types, this constraint will be modified to include them.
type ConcurrentMap ¶
type ConcurrentMap[TKey comparable, TValue any] struct { // contains filtered or unexported fields }
ConcurrentMap a concurrent map
func NewConcurrentMap ¶
func NewConcurrentMap[TKey comparable, TValue any]() *ConcurrentMap[TKey, TValue]
NewConcurrentMap creates a new instance of ConcurrentMap
func (*ConcurrentMap[TKey, TValue]) Delete ¶
func (m *ConcurrentMap[TKey, TValue]) Delete(key TKey)
Delete deletes the specified key from the map
func (*ConcurrentMap[TKey, TValue]) Foreach ¶
func (m *ConcurrentMap[TKey, TValue]) Foreach(f func(key TKey, value TValue))
Foreach iterates the map and passes the key and value to the given function
func (*ConcurrentMap[TKey, TValue]) Get ¶
func (m *ConcurrentMap[TKey, TValue]) Get(key TKey) (TValue, bool)
Get gets a value for the given key if it exists
func (*ConcurrentMap[TKey, TValue]) GetOrCompute ¶
func (m *ConcurrentMap[TKey, TValue]) GetOrCompute(key TKey, generator func() TValue) TValue
GetOrCompute gets a value from map if it does not exist compute the value from the given generator
func (*ConcurrentMap[TKey, TValue]) Len ¶
func (m *ConcurrentMap[TKey, TValue]) Len() int
Len gets the length of the underlying values
func (*ConcurrentMap[TKey, TValue]) Put ¶
func (m *ConcurrentMap[TKey, TValue]) Put(key TKey, value TValue) (TValue, bool)
Put puts a value to the map associate to the map and return the old value
func (*ConcurrentMap[TKey, TValue]) RemoveIf ¶
func (m *ConcurrentMap[TKey, TValue]) RemoveIf(evaluator func(key TKey, value TValue) bool) int
RemoveIf iterates the map and delete all items that the evaluator returns true returns number of items that were removed
type Controller ¶
type Controller interface {
ListActions() []Action
}
Controller a request controller that could provide a set of http.Handler to handle http requests based on the action name
type ControllerFunc ¶
type ControllerFunc func() []Action
ControllerFunc a function that implements Controller interface
func AsController ¶
func AsController(c interface{}) ControllerFunc
AsController enumerates all accessible member functions of c which has two parameters and *http.Request as the first one while *Response as the second one as Actions
func (ControllerFunc) ListActions ¶
func (f ControllerFunc) ListActions() []Action
ListActions adapt the ControllerFunc to Controller interface
type CustomHandler ¶
type CustomHandler interface { // PipelineWith returns a http.Handler that will execute the given handler // after the custom handler code is done. PipelineWith(handler http.Handler) http.Handler }
CustomHandler a handler that is executed after session is setup/restored
type CustomHandlerFunc ¶
CustomHandlerFunc a function that implements CustomHandler
func (CustomHandlerFunc) PipelineWith ¶
func (h CustomHandlerFunc) PipelineWith(handler http.Handler) http.Handler
PipelineWith implements CustomHandler interface
type DataCollector ¶
type DataCollector interface {
Collect(item interface{})
}
Data collector to collect query results
type DataCollectorCreator ¶
type DataCollectorCreator interface {
Create() DataCollector
}
Data collectors creator to create data collectors for query results
type DataCollectorFunc ¶
type DataCollectorFunc[T any] func(item *T)
func (DataCollectorFunc[T]) Collect ¶
func (collector DataCollectorFunc[T]) Collect(item interface{})
type DataRow ¶
type DataRow interface { ColumnTypes() ([]*sql.ColumnType, error) Columns() ([]string, error) Scan(dest ...interface{}) error }
DataRow data row, which can be used to scan values or get column information
type DbAccessor ¶
type DbAccessor struct {
// contains filtered or unexported fields
}
DbAccessor database accessor
func NewDbAccessor ¶
func NewDbAccessor(db *sql.DB) *DbAccessor
NewDbAccessor create a new instance of data accessor for the given db
func (*DbAccessor) BeginTxn ¶
func (accessor *DbAccessor) BeginTxn(ctx context.Context) (*DbTxn, error)
BeginTxn starts a new transaction with RepeatableRead isolation
func (*DbAccessor) BeginTxnWithIsolation ¶
func (accessor *DbAccessor) BeginTxnWithIsolation(ctx context.Context, isolation sql.IsolationLevel) (*DbTxn, error)
BeginTxnWithIsolation starts a new transaction
func (*DbAccessor) Execute ¶
func (accessor *DbAccessor) Execute(ctx context.Context, command string, args ...interface{}) (sql.Result, error)
Execute execute command towards db
func (*DbAccessor) GetOne ¶
func (accessor *DbAccessor) GetOne(ctx context.Context, proto interface{}) (interface{}, error)
GetOne query one entity based on the prototype
func (*DbAccessor) GetOneByKey ¶
func (accessor *DbAccessor) GetOneByKey(ctx context.Context, ty reflect.Type, key interface{}) (interface{}, error)
GetOneByKey query one entity based on the given key, the entity must have a single dimension primary key
func (*DbAccessor) QueryAll ¶
func (accessor *DbAccessor) QueryAll(ctx context.Context, query string, mapper RowMapper, args ...interface{}) ([]interface{}, error)
QueryAll execute sql query and return all entities based on the mapper
func (*DbAccessor) QueryAllWithCollector ¶
func (accessor *DbAccessor) QueryAllWithCollector(ctx context.Context, query string, mapper RowMapper, collector DataCollector, args ...interface{}) error
type DbClusterTxnStore ¶
type DbClusterTxnStore struct {
// contains filtered or unexported fields
}
DbClusterTxnStore an database based cluster transaction store implementation
func NewDbClusterTxnStore ¶
func NewDbClusterTxnStore(db *DbAccessor) *DbClusterTxnStore
NewDbClusterTxnStore create a new database based cluster transaction store
func (*DbClusterTxnStore) AddTxnParticipant ¶
func (store *DbClusterTxnStore) AddTxnParticipant(ctx context.Context, txnID string, partition int) error
AddTxnParticipant add a participant to a transaction
func (*DbClusterTxnStore) Close ¶
func (store *DbClusterTxnStore) Close() error
Close close all resources used by store
func (*DbClusterTxnStore) CreateTxn ¶
func (store *DbClusterTxnStore) CreateTxn(ctx context.Context, txnID string, t time.Time) (*ClusterTxn, error)
CreateTxn create a transaction
func (*DbClusterTxnStore) DeleteTxn ¶
func (store *DbClusterTxnStore) DeleteTxn(ctx context.Context, txnID string) error
DeleteTxn delete partition from store
func (*DbClusterTxnStore) GetTxn ¶
func (store *DbClusterTxnStore) GetTxn(ctx context.Context, txnID string) (*ClusterTxn, error)
GetTxn get transaction by ID
func (*DbClusterTxnStore) LeaseExpiredTxns ¶
func (store *DbClusterTxnStore) LeaseExpiredTxns(ctx context.Context, expireTime, leaseTimeout time.Time, items int) ([]*ClusterTxn, error)
LeaseExpiredTxns lease expired transactions, only expired and lease expired (or not lease) transactions are visible
func (*DbClusterTxnStore) ListParticipants ¶
func (store *DbClusterTxnStore) ListParticipants(ctx context.Context, txnID string) ([]*TxnParticipant, error)
ListParticipants list all participants in transaction
func (*DbClusterTxnStore) UpdateTxnState ¶
UpdateTxnState update transaction state
type DbTxn ¶
type DbTxn struct {
// contains filtered or unexported fields
}
DbTxn db transaction wrapper with context
func (*DbTxn) GetOneByKey ¶
GetOneByKey query one entity based on the key, the entity must have a sinle dimension key
func (*DbTxn) QueryAll ¶
func (txn *DbTxn) QueryAll(query string, mapper RowMapper, args ...interface{}) ([]interface{}, error)
QueryAll execute sql query and return all entities based on the mapper
func (*DbTxn) QueryAllWithCollector ¶
func (txn *DbTxn) QueryAllWithCollector(query string, mapper RowMapper, collector DataCollector, args ...interface{}) error
type DbUniqueIDGenerator ¶
type DbUniqueIDGenerator struct {
// contains filtered or unexported fields
}
DbUniqueIDGenerator database based unique id generator
func NewDbUniqueIDGenerator ¶
func NewDbUniqueIDGenerator(dbAccessor *DbAccessor) *DbUniqueIDGenerator
NewDbUniqueIDGenerator creates a db based unique id generator
func (*DbUniqueIDGenerator) NextUniqueID ¶
func (generator *DbUniqueIDGenerator) NextUniqueID(ctx context.Context, name string, partition int32) (UniqueID, error)
NextUniqueID generate a next unique id
type DistributedLocker ¶
type DistributedLocker interface { Lock(ctx context.Context) (LockContext, error) Unlock(lockCtx LockContext) }
type DistributedSharedLocker ¶
type DistributedSharedLocker interface {}
type EntityDescriptor ¶
type EntityDescriptor struct { InsertSQL string UpdateSQL string DeleteSQL string GetOneSQL string // contains filtered or unexported fields }
EntityDescriptor entity descriptor
func GetOrCreateEntityDescriptor ¶
func GetOrCreateEntityDescriptor(entityType reflect.Type) *EntityDescriptor
GetOrCreateEntityDescriptor get or create EntityDescriptor for the given type
func (*EntityDescriptor) GetInsertValues ¶
func (descriptor *EntityDescriptor) GetInsertValues(entity interface{}) []interface{}
GetInsertValues get insert values for the given entity
func (*EntityDescriptor) GetKeyValues ¶
func (descriptor *EntityDescriptor) GetKeyValues(entity interface{}) []interface{}
GetKeyValues get key value for the given entity
func (*EntityDescriptor) GetUpdateValues ¶
func (descriptor *EntityDescriptor) GetUpdateValues(entity interface{}) []interface{}
GetUpdateValues get update values for the given entity
type FieldValueGetter ¶
type FieldValueGetter struct {
// contains filtered or unexported fields
}
FieldValueGetter the field value pointer retriever
func NewFieldValueGetter ¶
func NewFieldValueGetter(fieldName string) *FieldValueGetter
NewFieldValueGetter creates a new FieldValueGetter object
type Float ¶ added in v1.4.9
Float is a constraint that permits any floating-point type. If future releases of Go add new predeclared floating-point types, this constraint will be modified to include them.
type Integer ¶ added in v1.4.9
Integer is a constraint that permits any integer type. If future releases of Go add new predeclared integer types, this constraint will be modified to include them.
type JwtKeyProvider ¶
type JwtKeyProvider interface { GetKey(ctx context.Context, issuer string) *rsa.PublicKey GetBackupKey(ctx context.Context, issuer string) *rsa.PublicKey }
JwtKeyProvider RSA public key provider for retrieving issuer public keys
type JwtUserClaims ¶
type JwtUserClaims struct { jwt.Claims Sid string `json:"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid,omitempty"` Name string `json:"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name,omitempty"` AccountName string `json:"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn,omitempty"` Roles []string `json:"http://schemas.microsoft.com/ws/2008/06/identity/claims/role,omitempty"` Domain string `json:"TenantId,omitempty"` SecurityToken string `json:"sectok,omitempty"` Parent string `json:"ParentAccountName,omitempty"` }
JwtUserClaims Microsoft claims spec compatible user claims
type JwtUserPrincipal ¶
type JwtUserPrincipal struct { UserPrincipal SecurityToken string DisplayName string Parent string Source string }
JwtUserPrincipal a user principal created from JWT token
type JwtUserProvider ¶
type JwtUserProvider struct {
// contains filtered or unexported fields
}
JwtUserProvider jwt token based user provider
func NewJwtUserProvider ¶
func NewJwtUserProvider(keyProvider JwtKeyProvider, userLoader UserPrincipalLoader) *JwtUserProvider
NewJwtUserProvider creates a new instances of jwt user provider
func (*JwtUserProvider) Authenticate ¶
func (provider *JwtUserProvider) Authenticate(request *http.Request) *UserPrincipal
func (*JwtUserProvider) GetName ¶
func (provider *JwtUserProvider) GetName() string
func (*JwtUserProvider) Load ¶
func (provider *JwtUserProvider) Load(domain, id string) *UserPrincipal
type KeepAliveMessageHandler ¶
type KeepAliveMessageHandler interface { // OnPingMessage when a ping message is received, no need to send back pong message, // which is done right after this handler OnPingMessage(session *WebSocketSession, text string) error // OnPongMessage when a pong message is received, this API will be called to notify the application OnPongMessage(session *WebSocketSession, text string) error }
KeepAliveMessageHandler websocket message handler to handle ping/pong messages for ping message, a pong message will be sent back after OnPingMessage is returned.
type LockContext ¶
type LockContext map[string]interface{}
type MyCluster ¶
type MyCluster struct {
// contains filtered or unexported fields
}
MyCluster MySQL based database cluster, up to 32 physical partitions, for cluster that requires more than 32 partitions, consider tidb or similar distributed database
func NewMyCluster ¶
func NewMyCluster(master *DbAccessor, partitions []*DbAccessor, txnTimeout int, idGen UniqueIDGenerator, partitionCalc PartitionCalculator) *MyCluster
NewMyCluster creates an instance of MyCluster
func NewMyClusterWithTxnStore ¶
func NewMyClusterWithTxnStore(txnStore TxnStore, partitions []*DbAccessor, txnTimeout int, idGen UniqueIDGenerator, partitionCalc PartitionCalculator) *MyCluster
NewMyClusterWithTxnStore create a new instance of MyCluster with given TxnStore
func (*MyCluster) Close ¶
func (cluster *MyCluster) Close()
Close close all resources that acquired by current instance
func (*MyCluster) CreateTransaction ¶
func (cluster *MyCluster) CreateTransaction(ctx context.Context) (*MyClusterTxn, error)
CreateTransaction creates a cluster transaction
func (*MyCluster) ExecuteOnAll ¶
func (cluster *MyCluster) ExecuteOnAll(ctx context.Context, query string, args ...interface{}) error
ExecuteOnAll execute query on all partitions
func (*MyCluster) GenerateKey ¶
GenerateKey generates and assign an unique id for the given entity
func (*MyCluster) GetAll ¶
func (cluster *MyCluster) GetAll(ctx context.Context, ty reflect.Type, query string, args ...interface{}) ([][]interface{}, error)
GetAll get all entities from all partition by the given prototype
func (*MyCluster) GetAllPartitions ¶
func (cluster *MyCluster) GetAllPartitions() []*DbAccessor
GetAllPartitions gets all physical partitions in cluster
func (*MyCluster) GetAllReduced ¶
func (cluster *MyCluster) GetAllReduced( ctx context.Context, ty reflect.Type, query string, reducer func([][]interface{}) []interface{}, args ...interface{}) ([]interface{}, error)
GetAllReduced get all entries and apply the reduce
func (*MyCluster) GetAllWithCollector ¶
func (*MyCluster) GetAnyPartition ¶
func (cluster *MyCluster) GetAnyPartition() *DbAccessor
GetAnyPartition gets a random partition from physical partitions
func (*MyCluster) GetDbAccessor ¶
func (cluster *MyCluster) GetDbAccessor(partition int32) *DbAccessor
GetDbAccessor get DbAccessor by partition
func (*MyCluster) GetDbAccessorByID ¶
func (cluster *MyCluster) GetDbAccessorByID(id int64) *DbAccessor
GetDbAccessorByID get DbAccessor by unique ID
func (*MyCluster) GetDbAccessorByKey ¶
func (cluster *MyCluster) GetDbAccessorByKey(partitionKey string) *DbAccessor
GetDbAccessorByKey get DbAccessor by partition key
func (*MyCluster) GetOne ¶
func (cluster *MyCluster) GetOne( ctx context.Context, ty reflect.Type, query string, aggregator func(interface{}, interface{}) interface{}, args ...interface{}) (interface{}, error)
GetOne query one entity by the given prototype
func (*MyCluster) GetPage ¶
func (cluster *MyCluster) GetPage( ctx context.Context, ty reflect.Type, query string, merger *PageMerger[any], args ...interface{}) ([]interface{}, error)
GetPage get a page of entities by the given prototype
func (*MyCluster) GetPartitionByKey ¶
GetPartitionByKey calculates the partition ID by the given partition key
func (*MyCluster) GetUniqueID ¶
func (cluster *MyCluster) GetUniqueID(ctx context.Context, entity interface{}, partition int32) (int64, error)
GetUniqueID gets a unique id for the given entity prototype
func (*MyCluster) GetUniqueIDByName ¶
func (cluster *MyCluster) GetUniqueIDByName(ctx context.Context, entityName string, partition int32) (int64, error)
GetUniqueIDByName gets a unique id from cluster for the given entity name and partition
func (*MyCluster) InsertByKey ¶
func (cluster *MyCluster) InsertByKey(ctx context.Context, partitionKey string, entity interface{}) error
InsertByKey insert entity to db based on given partition key
func (*MyCluster) InsertToAll ¶
InsertToAll insert entity to all partitions
func (*MyCluster) QueryAll ¶
func (cluster *MyCluster) QueryAll(ctx context.Context, query string, mapper RowMapper, args ...interface{}) ([][]interface{}, error)
QueryAll query all entities from all partitions by the given mapper
func (*MyCluster) QueryAllReduced ¶
func (cluster *MyCluster) QueryAllReduced( ctx context.Context, query string, mapper RowMapper, reducer func([][]interface{}) []interface{}, args ...interface{}) ([]interface{}, error)
QueryAllReduced query all entities and apply the reducer
func (*MyCluster) QueryAllWithCollector ¶
func (*MyCluster) QueryOne ¶
func (cluster *MyCluster) QueryOne( ctx context.Context, query string, mapper RowMapper, aggregator func(interface{}, interface{}) interface{}, args ...interface{}) (interface{}, error)
QueryOne query one entity with the given mapper
func (*MyCluster) QueryPage ¶
func (cluster *MyCluster) QueryPage( ctx context.Context, query string, mapper RowMapper, merger *PageMerger[any], args ...interface{}) ([]interface{}, error)
QueryPage query a page of entities by the given page merger
type MyClusterTxn ¶
type MyClusterTxn struct {
// contains filtered or unexported fields
}
MyClusterTxn cluster supported 2PC transaction
func (*MyClusterTxn) Close ¶
func (txn *MyClusterTxn) Close()
Close close and release all transactions
func (*MyClusterTxn) Commit ¶
func (txn *MyClusterTxn) Commit() error
Commit commit all participants
func (*MyClusterTxn) Delete ¶
func (txn *MyClusterTxn) Delete(entity interface{}) (sql.Result, error)
Delete delete the entity from database
func (*MyClusterTxn) DeleteAt ¶
func (txn *MyClusterTxn) DeleteAt(partition int32, entity interface{}) (sql.Result, error)
DeleteAt delete the specified entry from the given partition
func (*MyClusterTxn) DeleteFromAll ¶
func (txn *MyClusterTxn) DeleteFromAll(entity interface{}) ([]sql.Result, error)
DeleteFromAll delete the entry from all partitions
func (*MyClusterTxn) ExecuteAt ¶
func (txn *MyClusterTxn) ExecuteAt(partition int32, sql string, args ...interface{}) (sql.Result, error)
ExecuteAt execute the given query on a specific partition
func (*MyClusterTxn) ExecuteOnAll ¶
func (txn *MyClusterTxn) ExecuteOnAll(query string, args ...interface{}) ([]sql.Result, error)
ExecuteOnAll execute the given query on all partitions
func (*MyClusterTxn) GetTxnByID ¶
func (txn *MyClusterTxn) GetTxnByID(id int64) (*XATransaction, error)
GetTxnByID get an XATransaction by unique ID
func (*MyClusterTxn) GetTxnByPartition ¶
func (txn *MyClusterTxn) GetTxnByPartition(partition int32) (*XATransaction, error)
GetTxnByPartition get an XATransaction by partition number
func (*MyClusterTxn) InsertAt ¶
func (txn *MyClusterTxn) InsertAt(partition int32, entity interface{}) (sql.Result, error)
InsertAt insert an entity to the given partition
func (*MyClusterTxn) InsertToAll ¶
func (txn *MyClusterTxn) InsertToAll(entity interface{}) ([]sql.Result, error)
InsertToAll insert an entry to all partitions
func (*MyClusterTxn) Rollback ¶
func (txn *MyClusterTxn) Rollback() error
Rollback rollback all participants
func (*MyClusterTxn) Update ¶
func (txn *MyClusterTxn) Update(entity interface{}) (sql.Result, error)
Update update entity to database
func (*MyClusterTxn) UpdateAt ¶
func (txn *MyClusterTxn) UpdateAt(partition int32, entity interface{}) (sql.Result, error)
UpdateAt update entity at the specific partition
func (*MyClusterTxn) UpdateToAll ¶
func (txn *MyClusterTxn) UpdateToAll(entity interface{}) ([]sql.Result, error)
UpdateToAll update entity to all partitions
type Ordered ¶ added in v1.4.9
Ordered is a constraint that permits any ordered type: any type that supports the operators < <= >= >. If future releases of Go add new ordered types, this constraint will be modified to include them.
type PageMerger ¶
type PageMerger[T any] struct { // contains filtered or unexported fields }
PageMerger a tool to merge multiple paged query results into one page
func NewPageMerger ¶
func NewPageMerger[T any](pageSize int, comparer Comparer[T]) *PageMerger[T]
NewPageMerger create a new page merger
func (*PageMerger[T]) Merge ¶
func (m *PageMerger[T]) Merge(lists ...[]T) []T
Merge merge lists into a single sorted list and only return the top `pageSize` items of all lists
type PageQuery ¶ added in v1.4.9
type PageQuery[T any, TPrimaryKey any, TSecondaryKey any] struct { Cluster *MyCluster CountingQueryText string CountingQueryArgsConfigurer func() []interface{} QuerySetup func(sql *strings.Builder) ([]interface{}, bool) PrimaryKeyName string SecondaryKeyName string PrimaryKeyParser func(value string) (TPrimaryKey, bool) SecondaryKeyParser func(value string) (TSecondaryKey, bool) PrimaryKeyGetter func(t *T) TPrimaryKey SecondaryKeyGetter func(t *T) TSecondaryKey PrimaryKeyComparer Comparer[TPrimaryKey] SecondaryKeyComparer Comparer[TSecondaryKey] }
type PartitionCalculateFunc ¶
PartitionCalculateFunc partition calculate function, implements PartitionCalculator
func (PartitionCalculateFunc) GetPartition ¶
func (calc PartitionCalculateFunc) GetPartition(key string) int32
GetPartition implements PartitionCalculator
type PartitionCalculator ¶
PartitionCalculator partition key calculator
type PooledID ¶
type PooledID struct { Name string `col:"name" dtags:"key,nogen"` Partition int32 `col:"partition"` PooledID int64 `col:"pooled_id"` }
PooledID unique id pooled ID record, requires the following table / create table `pooled_id` ( / `name` varchar(200) not null, / `partition` int not null, / `pooled_id` bigint not null, / constraint `pk_id_generator` primary key (`name`, `partition`) / );
type Queryable ¶
type Queryable interface { QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row }
Queryable a queryable object that could be a Connection, DB or Tx
type Response ¶
type Response struct { Writer http.ResponseWriter // contains filtered or unexported fields }
Response web response
func (*Response) DoneWithContent ¶
DoneWithContent sets the status, content-type header and writes the content to response
func (*Response) DoneWithError ¶
DoneWithError response an error page based on errorTemplate to the client
func (*Response) DoneWithJSON ¶
DoneWithJSON sets the status and write the model as json
func (*Response) DoneWithRedirect ¶
DoneWithRedirect redirects to the specified url
func (*Response) DoneWithTemplate ¶
DoneWithTemplate sets the status and write the model with the given template name as response, the content type is defaulted to text/html
func (*Response) SetNoCache ¶
func (r *Response) SetNoCache()
SetNoCache sets headers for the client not to cache the response
type RowMapper ¶
RowMapper maps a row to an object
func NewSmartMapper ¶
NewSmartMapper creates a smart row mapper for data row
type RowMapperFunc ¶
RowMapperFunc a function that implements RowMapper
func (RowMapperFunc) Map ¶
func (mapper RowMapperFunc) Map(row DataRow) (interface{}, error)
Map implements the RowMapper interface
type SecurityHandler ¶
type SecurityHandler struct {
// contains filtered or unexported fields
}
SecurityHandler a http handler to do both authentication and authorization for requests
func NewSecurityHandler ¶
func NewSecurityHandler() *SecurityHandler
NewSecurityHandler creates an instance of SecurityHandler object without any user providers and with nil AuthorizationManager
func (*SecurityHandler) AddUserProvider ¶
func (handler *SecurityHandler) AddUserProvider(userProvider UserProvider) *SecurityHandler
AddUserProvider add a user provider to the security handler
func (*SecurityHandler) ServeHTTP ¶
func (handler *SecurityHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request)
ServeHTTP implements the http.Handler interface
func (*SecurityHandler) WithAuthz ¶
func (handler *SecurityHandler) WithAuthz(authz AuthorizationManager) *SecurityHandler
WithAuthz specify the AuthorizationManager to be used by this handler
func (*SecurityHandler) WithLoginURL ¶
func (handler *SecurityHandler) WithLoginURL(loginURL string) *SecurityHandler
WithLoginURL the URL to redirect if the access is denied
func (*SecurityHandler) WithPipeline ¶
func (handler *SecurityHandler) WithPipeline(h http.Handler) *SecurityHandler
WithPipeline specify the http.Handler to be called if the request passes the security check
type Session ¶
Session a HTTP session
func GetSession ¶
GetSession helper function for getting session from request
func (*Session) Deserialize ¶
Deserialize de-serializes the bytes into session data
func (*Session) GetAsFlashValue ¶
GetAsFlashValue gets the value that is associated with the key and remove the value if the key existing, this returns the value and the key existing indicator
func (*Session) GetValue ¶
GetValue gets the value which is associated with the key, returns the value and key existing indicator
type SessionStore ¶
type SessionStore interface { // Save saves the session with timeout, the session cannot be // returned by Get after the give timeout duration passed, while the // timeout need to be reset at each time the session is saved. // if the session's IsValid is set to false, after saved, the // session should never be returned by Get. Save(session *Session, timeout time.Duration) error // Get gets the session with the given ID, returns the session // if the session is still valid, otherwise, (nil, ErrSessionNotFound) // will be returned Get(id string) (*Session, error) // Close closes the session store and release the resources that // the session store owns Close() }
SessionStore interface for storing sessions
func NewFileSessionStore ¶
func NewFileSessionStore(directory string) (SessionStore, error)
NewFileSessionStore creates a file session store
func NewInMemorySessionStore ¶
func NewInMemorySessionStore() SessionStore
NewInMemorySessionStore creates an in memory session store
func NewRedisSessionStore ¶
func NewRedisSessionStore(cli *redis.Client) SessionStore
NewRedisSessionStore creates a new redis based session store
type SharedTemplateDetector ¶
SharedTemplateDetector detector used to check if the given path is a shared template or not
type Signed ¶ added in v1.4.9
Signed is a constraint that permits any signed integer type. If future releases of Go add new predeclared signed integer types, this constraint will be modified to include them.
type SkinManager ¶
type SkinManager struct {
// contains filtered or unexported fields
}
SkinManager a TemplateManager is mapped to a skin, skin manager manages TemplateManagers by names.
func NewSkinManager ¶
func NewSkinManager(defaultSkin *TemplateManager) *SkinManager
NewSkinManager creates a skin manager object
func (*SkinManager) AddSkin ¶
func (skinMgr *SkinManager) AddSkin(name string, tmplMgr *TemplateManager)
AddSkin adds a skin
func (*SkinManager) ApplySelector ¶
func (skinMgr *SkinManager) ApplySelector(request *http.Request) (*TemplateManager, string)
ApplySelector find skin by applying selector, if selector is not configured default skin will be returned, if the skin name returned by the selector cannot be found, this returns nil
func (*SkinManager) GetDefaultSkin ¶
func (skinMgr *SkinManager) GetDefaultSkin() *TemplateManager
GetDefaultSkin gets the default skin
func (*SkinManager) GetSkin ¶
func (skinMgr *SkinManager) GetSkin(name string) (*TemplateManager, bool)
GetSkin find skin by name
func (*SkinManager) GetSkinOrDefault ¶
func (skinMgr *SkinManager) GetSkinOrDefault(name string) *TemplateManager
GetSkinOrDefault gets the skin with the given name if it's not found return the default skin
func (*SkinManager) RemoveSkin ¶
func (skinMgr *SkinManager) RemoveSkin(name string)
RemoveSkin removes a skin
func (*SkinManager) WithSelector ¶
func (skinMgr *SkinManager) WithSelector(selector SkinSelector)
WithSelector sets the skin selector for the skin manager
type SkinSelector ¶
SkinSelector returns a skin name based on the request object
type SkinSelectorFunc ¶
SkinSelectorFunc converts a function to SkinSelector interface
type SliceCollector ¶
type SliceCollector[T any] struct { Results []*T }
func NewSliceCollector ¶
func NewSliceCollector[T any]() *SliceCollector[T]
func (*SliceCollector[T]) Collect ¶
func (collector *SliceCollector[T]) Collect(item interface{})
type SliceCollectorCreator ¶
type SliceCollectorCreator[T any] struct { Collectors []*SliceCollector[T] }
func NewSliceCollectorCreator ¶
func NewSliceCollectorCreator[T any]() *SliceCollectorCreator[T]
func (*SliceCollectorCreator[T]) Create ¶
func (creator *SliceCollectorCreator[T]) Create() DataCollector
func (*SliceCollectorCreator[T]) GetResults ¶
func (creator *SliceCollectorCreator[T]) GetResults() [][]*T
func (*SliceCollectorCreator[T]) MergeResults ¶
func (creator *SliceCollectorCreator[T]) MergeResults(merger *PageMerger[*T]) []*T
type TableNameResolver ¶
TableNameResolver resolves a struct name to table name
type TableNameResolverFunc ¶
TableNameResolverFunc a function that implements TableNameResolver
func (TableNameResolverFunc) Resolve ¶
func (resolver TableNameResolverFunc) Resolve(name string) string
Resolve resolves struct name to table name
type TemplateConfigFunc ¶
TemplateConfigFunc shared templates config function
type TemplateManager ¶
type TemplateManager struct {
// contains filtered or unexported fields
}
TemplateManager manages the templates by groups and update template group on-demand based on the template file update timestamp
func NewTemplateManager ¶
func NewTemplateManager(dir, suffix string, refreshInterval time.Duration, configFunc TemplateConfigFunc, sharedTemplateDetector SharedTemplateDetector) *TemplateManager
NewTemplateManager creates a template manager for the given dir
func (*TemplateManager) Close ¶
func (manager *TemplateManager) Close()
Close closes the template manager and release all resources
func (*TemplateManager) GetTemplate ¶
func (manager *TemplateManager) GetTemplate(name string) (*template.Template, bool)
GetTemplate retrieve a template with the specified name from template manager, this returns the template and a boolean value to indicate if the template is found or not
type Txn ¶
type Txn interface { Insert(entity interface{}) (sql.Result, error) Update(entity interface{}) (sql.Result, error) Delete(entity interface{}) (sql.Result, error) Execute(sql string, args ...interface{}) (sql.Result, error) GetOneByKey(ty reflect.Type, key interface{}) (interface{}, error) GetOne(proto interface{}) (interface{}, error) QueryOne(sql string, mapper RowMapper, args ...interface{}) (interface{}, error) QueryAll(sql string, mapper RowMapper, args ...interface{}) ([]interface{}, error) QueryAllWithCollector(sql string, mapper RowMapper, collector DataCollector, args ...interface{}) error }
Txn an abstraction for db transaction as well as cluster based db transaction
type TxnParticipant ¶
type TxnParticipant struct { TxnID string `col:"txn_id" dtags:"multikey"` Partition int `col:"partition" dtags:"multikey"` State int `col:"state"` }
TxnParticipant cluster transaction participant
type TxnStore ¶
type TxnStore interface { // CreateTxn create a transaction entity CreateTxn(ctx context.Context, txnID string, t time.Time) (*ClusterTxn, error) // GetTxn get transaction entity by ID GetTxn(ctx context.Context, txnID string) (*ClusterTxn, error) // UpdateTxnState update transaction state UpdateTxnState(ctx context.Context, txnID string, state int) error // AddTxnParticipant add a participant to a transaction AddTxnParticipant(ctx context.Context, txnID string, partition int) error // DeleteTxn delete partition from store DeleteTxn(ctx context.Context, txnID string) error // LeaseExpiredTxns lease expired transactions, only expired and lease expired (or not lease) transactions are visible LeaseExpiredTxns(ctx context.Context, expireTime, leaseTimeout time.Time, items int) ([]*ClusterTxn, error) // ListParticipants list all participants in transaction ListParticipants(ctx context.Context, txnID string) ([]*TxnParticipant, error) // Close close all resources used by store Close() error }
TxnStore a cluster transaction entity store to keep cluster transaction states
type UniqueID ¶
type UniqueID struct {
Value int64 // format [PooledID][Partition][SegmentedID]
}
UniqueID global unique id for a given namespace in cluster
func NewUniqueID ¶
NewUniqueID create a new unique id based on the pooledID, partition and segmentedID
type UniqueIDGenerator ¶
type UniqueIDGenerator interface {
NextUniqueID(ctx context.Context, name string, partition int32) (UniqueID, error)
}
UniqueIDGenerator unique id generator interface
type UniqueIDPool ¶
UniqueIDPool unique id pool
func (*UniqueIDPool) UpdatePooledID ¶
func (pool *UniqueIDPool) UpdatePooledID(partition int32, pooledID int64) error
UpdatePooledID update pooled id for the given partition
type Unsigned ¶ added in v1.4.9
Unsigned is a constraint that permits any unsigned integer type. If future releases of Go add new predeclared unsigned integer types, this constraint will be modified to include them.
type UserPrincipal ¶
type UserPrincipal struct { // ID user id ID string // Domain the domain of the user principal Domain string // Name user's printable name Name string // Provider user provider Provider string // Roles roles for the user Roles []string // Self pointing to the object that owns this object // this makes the UserPrincipal extensible and embeddable // The container object can put its pointer into this field // and could be deferenced by the application code Self interface{} }
UserPrincipal the security principal of the http session
func GetUser ¶
func GetUser(request *http.Request) *UserPrincipal
GetUser gets the UserPrincipal for the request
type UserPrincipalLoader ¶
type UserPrincipalLoader interface {
Load(domain, id string) *UserPrincipal
}
UserPrincipalLoader loads a user principal by user domain and id
type UserPrincipalLoaderFunc ¶
type UserPrincipalLoaderFunc func(domain, id string) *UserPrincipal
UserPrincipalLoaderFunc delegates function to UserPrincipalLoader interface
func (UserPrincipalLoaderFunc) Load ¶
func (f UserPrincipalLoaderFunc) Load(domain, id string) *UserPrincipal
type UserProvider ¶
type UserProvider interface { // GetName gets the name of the provider GetName() string // Authenticate authenticates the incoming request and // returns the UserPrincipal object if security token // is found and resolvable by the user provider or nil // if nothing can be resolved Authenticate(request *http.Request) *UserPrincipal //Load loads the user by the specified domain and id Load(domain, id string) *UserPrincipal }
UserProvider an interface used by the framework to resolve UserPrincipal from incoming request and also used by loading the UserPrincipal in authorized mode by given user id and user domain
type WebServer ¶
type WebServer struct {
// contains filtered or unexported fields
}
WebServer a web server that supports auth & authz, logging, session and web sockets
func NewWebServer ¶
func NewWebServer(listenAddr string, skinMgr *SkinManager) *WebServer
NewWebServer creates a web server instance to listen on the specified address
func (*WebServer) AddStaticResource ¶
AddStaticResource adds a static resource folder to the server with the given prefix, the prefix must be in format of "/prefix/"
func (*WebServer) AddUserProvider ¶
func (server *WebServer) AddUserProvider(provider UserProvider) *WebServer
AddUserProvider adds a user provider to security handler
func (*WebServer) AddWsEndoint ¶
func (server *WebServer) AddWsEndoint(endpoint string, listener WebSocketListener) *WebServer
AddWsEndoint adds a web socket endpoint to the server
func (*WebServer) AddWsHandler ¶
func (server *WebServer) AddWsHandler(endpoint string, handler *WebSocketHandler) *WebServer
AddWsHandler adds a web socket handler to server
func (*WebServer) HandleFunc ¶
func (server *WebServer) HandleFunc(path string, f func(w http.ResponseWriter, r *http.Request)) *WebServer
HandleFunc register a handle function for a path pattern
func (*WebServer) RegisterController ¶
func (server *WebServer) RegisterController(name string, controller Controller) error
RegisterController register a controller for the standard routing
func (*WebServer) WithAuthz ¶
func (server *WebServer) WithAuthz(authz AuthorizationManager) *WebServer
WithAuthz specify the AuthorizationManager to be used by this handler
func (*WebServer) WithCaptcha ¶
WithCaptcha setup a captcha generator at the given "path" in a 240 x 80 image with six digits chanllege
func (*WebServer) WithCaptchaCustom ¶
WithCaptchaCustom setup a captcha generator at the given path with custom digits, width and height
func (*WebServer) WithCustomHandler ¶
func (server *WebServer) WithCustomHandler(handler CustomHandler) *WebServer
WithCustomHandler set or chains a handler to custom handlers chain, the new CustomHandler will be added to the tail of custom handlers chain.
func (*WebServer) WithLoginURL ¶
WithLoginURL the URL to redirect if the access is denied
func (*WebServer) WithRequestTimeout ¶
WithRequestTimeout set request timeout in seconds for each individual requests
func (*WebServer) WithSessionOptions ¶
func (server *WebServer) WithSessionOptions(store SessionStore, timeout time.Duration, valueTypes ...interface{}) *WebServer
WithSessionOptions setup the session options including the session store and session timeout interval
func (*WebServer) WithStandardRouting ¶
WithStandardRouting setup a routing as "prefix" + "/{controller:[_a-zA-Z][_a-zA-Z0-9]*}/{action:[_a-zA-Z][_a-zA-Z0-9]*}" and the web server will route the requests based on the registered controllers.
type WebSocketHandler ¶
type WebSocketHandler struct { MessageLimit int64 ReadTimeout time.Duration WriteTimeout time.Duration Listener WebSocketListener WriteCompression bool CheckOrigin func(*http.Request) bool }
WebSocketHandler Web socket handler have handler.Handle for router to enable web socket endpoints
func (*WebSocketHandler) Handle ¶
func (handler *WebSocketHandler) Handle(writer http.ResponseWriter, request *http.Request)
Handle handles the incomping web requests and try to upgrade the request into a websocket connection
type WebSocketListener ¶
type WebSocketListener interface { // OnConnect when a connection is established OnConnect(session *WebSocketSession) // OnTextMessage when a text message is available in the channel OnTextMessage(session *WebSocketSession, text string) // OnBinaryMessage when a binary message is available in the channel OnBinaryMessage(session *WebSocketSession, data []byte) // OnClose when the channel is broken or closed by remote OnClose(session *WebSocketSession, reason int) }
WebSocketListener web socket listener that could be used to listen on a specific web socket endpoint
type WebSocketSession ¶
type WebSocketSession struct { RemoteAddr string User *UserPrincipal Session *Session Context map[string]interface{} // contains filtered or unexported fields }
WebSocketSession a connected web socket session
func (*WebSocketSession) Close ¶
func (session *WebSocketSession) Close() error
Close close the underlying connection of the WebSocketSession
func (*WebSocketSession) SendBinaryMessage ¶
func (session *WebSocketSession) SendBinaryMessage(data []byte) error
SendBinaryMessage sends a binary message to the remote, a more convenient version of SendMessage
func (*WebSocketSession) SendMessage ¶
func (session *WebSocketSession) SendMessage(msgType int, data []byte) error
SendMessage sends a message with the given type
func (*WebSocketSession) SendTextMessage ¶
func (session *WebSocketSession) SendTextMessage(text string) error
SendTextMessage sends a text message to the remote, a more convenient version of SendMessage
type XATransaction ¶
type XATransaction struct {
// contains filtered or unexported fields
}
XATransaction MySQL XA transaction support
func (*XATransaction) Delete ¶
func (xa *XATransaction) Delete(entity interface{}) (sql.Result, error)
Delete delete entity from db
func (*XATransaction) Execute ¶
func (xa *XATransaction) Execute(command string, args ...interface{}) (sql.Result, error)
Execute execute command towards db
func (*XATransaction) GetOne ¶
func (xa *XATransaction) GetOne(proto interface{}) (interface{}, error)
GetOne query one entity based on the keys in prototype
func (*XATransaction) GetOneByKey ¶
func (xa *XATransaction) GetOneByKey(ty reflect.Type, key interface{}) (interface{}, error)
GetOneByKey query one entity based on the prototype and the single dimension key
func (*XATransaction) Insert ¶
func (xa *XATransaction) Insert(entity interface{}) (sql.Result, error)
Insert insert entity to db
func (*XATransaction) QueryAll ¶
func (xa *XATransaction) QueryAll(query string, mapper RowMapper, args ...interface{}) ([]interface{}, error)
QueryAll execute sql query and return all entities based on the mapper
func (*XATransaction) QueryAllWithCollector ¶
func (xa *XATransaction) QueryAllWithCollector(query string, mapper RowMapper, collector DataCollector, args ...interface{}) error
type XaTxnID ¶
type XaTxnID struct { FormatID int `col:"formatID"` GlobalIDLength int `col:"gtrid_length"` BranchIDLength int `col:"bqual_length"` Data string `col:"data"` }
XaTxnID xa transaction id format
type ZkLock ¶
type ZkLock struct {
// contains filtered or unexported fields
}
ZkLock zookeeper based distributed lock This lock does not rely on sequential numbers, but may lead to starvation issue
func (*ZkLock) Lock ¶
func (lock *ZkLock) Lock(ctx context.Context) (LockContext, error)
Lock lock or return error if not able to lock
func (*ZkLock) Unlock ¶
func (lock *ZkLock) Unlock(lockCtx LockContext)
Unlock release the lock, alias of Release
type ZkLock2 ¶
type ZkLock2 struct {
// contains filtered or unexported fields
}
ZkLock zookeeper based distributed lock
func NewZkLock2 ¶
NewZkLock creates a new ZkLock2 on the given path
func (*ZkLock2) Unlock ¶
func (lock *ZkLock2) Unlock(lockCtx LockContext)
type ZkRWLock ¶
type ZkRWLock struct {
// contains filtered or unexported fields
}
ZkRWLock zookeeper based reader/writer lock
func NewZkRWLock ¶
NewZkRWLock creates a zookeeper reader/writer lock on the given path
func (*ZkRWLock) Lock ¶
func (rwLock *ZkRWLock) Lock(ctx context.Context) (LockContext, error)
Lock acquires writer lock
func (*ZkRWLock) RLock ¶
func (rwLock *ZkRWLock) RLock(ctx context.Context) (LockContext, error)
RLock try to acquire reader lock
func (*ZkRWLock) RUnlock ¶
func (rwLock *ZkRWLock) RUnlock(lockCtx LockContext)
RUnlock release reader lock that is acquired
func (*ZkRWLock) Unlock ¶
func (rwLock *ZkRWLock) Unlock(lockCtx LockContext)
Unlock release writer lock
type ZkRWLock2 ¶
type ZkRWLock2 struct {
// contains filtered or unexported fields
}
func (*ZkRWLock2) RUnlock ¶
func (lock *ZkRWLock2) RUnlock(lockCtx LockContext)
func (*ZkRWLock2) Unlock ¶
func (lock *ZkRWLock2) Unlock(lockCtx LockContext)
Source Files ¶
- cluster_txn.go
- concurrent_map.go
- constants.go
- constraints.go
- context.go
- crypto.go
- database.go
- db_cluster_txn_store.go
- entity.go
- jwt_user_provider.go
- logging.go
- mycluster.go
- page_merger.go
- page_query.go
- query_helper.go
- reflector.go
- security.go
- session.go
- session_file.go
- session_inmem.go
- session_redis.go
- smart_row_mapper.go
- template.go
- txn.go
- unique_id.go
- utils.go
- webserver.go
- websocket.go
- writer.go
- zklock.go
- zklock2.go
- zkrwlock.go
- zkrwlock2.go