rice

package module
v0.0.22 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2022 License: MIT Imports: 44 Imported by: 2

README

rice

import "github.com/chirichan/rice"
go mod tidy

Usage

Database

Postgresql 初始化

pg, err := rice.NewPostgres("postgres://postgres:123456@localhost:5432/test?sslmode=disable")
if err != nil {
	return err
}
defer pg.Close()

MariaDB 初始化

mariadb, err := rice.NewMaria("root:root@tcp(localhost:3306)/test?parseTime=True&loc=Local&charset=utf8mb4")
if err != nil {
	return err
}
defer mariadb.Close()

Redis 初始化

rdb, err := rice.NewRedis("localhost:6379")
if err != nil {
	return err
}
defer rdb.Close()

Pretty 封装了 database/sql 标准库里 sql.DBsql.Tx 共有的一些方法,使用 Pretty 时可以在 repo 的上一层初始化,使 repo 层既可以执行 sql.DB 的方法,也可以执行 sql.Tx 的方法,下面是示例。

package repo

type Repo struct {
	Pretty
}

func NewRepo(db Pretty) Repo {
	return Repo{Pretty: db}
}

func (r Repo) WithTx(tx Pretty) Repo {
	return Repo{Pretty: tx}
}

func (r Repo) Create() error { return nil }

func (r Repo) Update() error { return nil }

func (r Repo) Find() error { return nil }
package usecase

func UseCaseDB() {

	db := NewMariaDB()

	dbRepo := NewRepo(db)

	dbRepo.Find()
}

func UseCaseTx() error {

	tx, _ := NewMariaTx()
	defer tx.Rollback()

	txRepo := NewRepo(tx)

	err := txRepo.Create()
	if err != nil {
		return err
	}

	err = txRepo.Update()
	if err != nil {
		return err
	}

	if err := tx.Commit(); err != nil {
		return err
	}

	return nil
}

Install

go install github.com/chirichan/rice/cmd/pwdgen@latest

Documentation

Index

Constants

View Source
const (
	// LowerLetters is the list of lowercase letters.
	LowerLetters = "abcdefghijklmnopqrstuvwxyz"

	// UpperLetters is the list of uppercase letters.
	UpperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

	// Digits is the list of permitted digits.
	Digits = "0123456789"

	// Symbols is the list of symbols.
	Symbols = "~!@#$%^&*()_+`-={}|[]\\:\"<>?,./"
)
View Source
const (
	GmailSmtp    = "smtp.gmail.com"
	GmailTLSPort = 587
	GmailSSLPort = 465
)

Variables

View Source
var (
	// Cert is a self signed certificate
	Cert tls.Certificate
	// CertPool contains the self signed certificate
	CertPool *x509.CertPool
)
View Source
var (
	ErrInvalidTransition = errors.New("invalid transition")
)
View Source
var (
	Logger *zerolog.Logger = &zerolog.Logger{}
)

Functions

func BCryptCompareHashAndPassword

func BCryptCompareHashAndPassword(pwd, hash string) bool

BCryptCompareHashAndPassword true or false

func BCryptGenerateFromPassword

func BCryptGenerateFromPassword(pwd string) (string, error)

BCryptGenerateFromPassword generate hash from password

func BetweenDays

func BetweenDays(startTime, endTime time.Time) int64

BetweenDays 两个时间之间隔了多少天 startTime >= endTime

func ByteString

func ByteString(b []byte) string

ByteString []byte to string

func BytesNewBufferString

func BytesNewBufferString(b []byte) string

BytesNewBufferString []byte to string

func CertInit

func CertInit(certPEM, keyPEM []byte) error

func CheckPassword

func CheckPassword(pwd string) error

func CronRun

func CronRun(ctx context.Context, corn string, task ...func()) error

func CronRunM

func CronRunM(ctx context.Context, corn string, task ...func()) error

func DeleteStruct

func DeleteStruct(key string) error

func DeleteStructByPrefix

func DeleteStructByPrefix(prefix string) error

func ErrorWrap

func ErrorWrap(w http.ResponseWriter, code int, err error, msg ...string) error

func Filter

func Filter[T any](objs []T, filter func(obj T) bool) []T

Filter filter one slice

func First

func First[T any](objs []T) (T, bool)

First make return first for slice

func FullPassword

func FullPassword(level, length int) (string, error)

func GetHostname

func GetHostname() string

func GetString

func GetString(key string) string

func GetStruct

func GetStruct[T any](key string) (T, error)

GetStruct 如果 key 不存在,返回 error; 如果 key 为空,返回零值

func HGetStruct

func HGetStruct[T any](key, field string) (T, error)

func HMCompare

func HMCompare(h1, m1, h2, m2 int) bool

HMCompare 如果 1 > 2 return true 小时和分钟 比较大小

func HSetStruct

func HSetStruct(key, field string, data any) error

func HttpGet

func HttpGet[T any](url string) (T, error)

func In

func In[T comparable](e T, s []T) bool

In e 在 s 中吗? true 在,false 不在

func LoggerInit

func LoggerInit(level, path string)

func Map

func Map[T any, K any](objs []T, mapper func(obj T) ([]K, bool)) []K

Map one slice

func MaxNumber

func MaxNumber[T Numbers](n ...T) T

MaxNumber booleans, numbers, strings, pointers, channels, arrays

func MinNumber

func MinNumber[T Numbers](n ...T) T

func NewGmailAuth

func NewGmailAuth(username, password string) smtp.Auth

func NewGrpcServer

func NewGrpcServer(ctx context.Context, port string, server *grpc.Server)

NewGrpcServer -.

func NewLumberjackLogger

func NewLumberjackLogger(fileName string, opts ...LumberjackOption) io.Writer

func NextStringId

func NextStringId() string

func NotIn

func NotIn[T comparable](e T, s []T) bool

NotIn e 不在 s 中吗? true 不在, false 在

func Pageination

func Pageination[T any](page, pageSize int, s []T) []T

Pageination 切片分页

func RandInt

func RandInt(max int64) (int64, error)

RandInt 生成一个真随机数

func RemoveDuplicates

func RemoveDuplicates[T comparable](s1 []T) []T

RemoveDuplicates slice 去重

func RemoveDuplicatesInPlace

func RemoveDuplicatesInPlace(userIDs []int64) []int64

RemoveDuplicatesInPlace slice 就地去重

func SetString

func SetString(key, value string, expiration ...time.Duration) error

func SetStruct

func SetStruct(key string, data any, expiration ...time.Duration) error

func SliceDifference

func SliceDifference[T comparable](a, b []T) []T

SliceDifference 取 a 中有,而 b 中没有的

func SliceDifferenceBoth

func SliceDifferenceBoth[T comparable](slice1, slice2 []T) []T

SliceDifferenceBoth 取 slice1, slice2 的差集

func SliceIn

func SliceIn[T comparable](e T, s []T) bool

SliceIn e 是否在 s 中

func SliceIntersection

func SliceIntersection[T comparable](s1, s2 []T) (inter []T)

SliceIntersection 两个 slice 的交集

func SlicePtrToSlice

func SlicePtrToSlice[T any](s []*T) []T

func SliceRemoveIndex

func SliceRemoveIndex[T any](s []T, index int) []T

SliceRemoveIndex 移除 slice 中的一个元素

func SliceRemoveIndexUnOrder

func SliceRemoveIndexUnOrder[T any](s []T, i int) []T

SliceRemoveIndexUnOrder 移除 slice 中的一个元素(无序,但效率高)

func SliceReverse

func SliceReverse[T any](slice []T)

SliceReverse 反转 slice

func SliceToSlicePtr

func SliceToSlicePtr[T any](s []T) []*T

func StrconvFormatInt

func StrconvFormatInt(i int64) string

StrconvFormatInt 1645270804 to "1645270804"

func StrconvParseFloat

func StrconvParseFloat(i int) (float64, error)

StrconvParseFloat int/100 to float64 保留 2 位小数点 example: 2333 -> 23.33

func StrconvParseInt

func StrconvParseInt(s string) (int64, error)

StrconvParseInt "1645270804" to 1645270804

func StringByte

func StringByte(s string) []byte

StringByte string to []byte

func StringByteUnsafe

func StringByteUnsafe(s string) []byte

StringByteUnsafe string to []byte

func TickerRun

func TickerRun(ctx context.Context, d time.Duration, task ...Task) error

func TickerRunContext

func TickerRunContext(ctx context.Context, d time.Duration, task ...TaskContext) error

TickerRunContext 立即开始以 ticker 的方式执行 task

func TickerRunWithStartTimeContext

func TickerRunWithStartTimeContext(ctx context.Context, wg *sync.WaitGroup, tm time.Time, d time.Duration, task ...TaskContext) error

TickerRunWithStartTimeContext 到达 tm 时间之后,开始以 tikcer 的方式执行 task

func TimeCompare

func TimeCompare(t1, t2 time.Time) bool

TimeCompare 如果 t1>t2, return true, 如果 t1 <= t2, return false

func TimeExistIntersection

func TimeExistIntersection(startTime, endTime time.Time, anotherStartTime, anotherEndTime time.Time) bool

TimeExistIntersection 两个时间段是否有交集 false 没有交集,true 有交集

func TimeFormat

func TimeFormat(tm time.Time) string

TimeFormat time.Time to "2006-01-02 15:04:05"

func TimeFormatDate

func TimeFormatDate(tm time.Time) string

TimeFormatDate time to date

func TimeNowFormat

func TimeNowFormat() string

TimeNowFormat time.Time to "2006-01-02 15:04:05"

func TimeParseDate

func TimeParseDate(date string) (time.Time, error)

TimeParseDate string date to time date

func TimeParseDatetime

func TimeParseDatetime(datetime string) (time.Time, error)

func TimeUnixFormatDate

func TimeUnixFormatDate(timestamp int64) string

TimeUnixFormatDate timestamp to date

func TimeUnixFormatDatetime

func TimeUnixFormatDatetime(timestamp int64) string

TimeUnixFormatDatetime time to datetime

func TimerRun

func TimerRun(ctx context.Context, tm time.Time, task ...Task) error

func TimestampExistIntersection

func TimestampExistIntersection(startTime, endTime int64, anotherStartTime, anotherEndTime int64) bool

TimestampExistIntersection 两个时间段是否有交集 false 没有交集,true 有交集

func TodayZeroTime

func TodayZeroTime() time.Time

func TodayZeroTimestamp

func TodayZeroTimestamp() int64

func UnWrapBody

func UnWrapBody[T any](r *http.Request) (*T, error)

func UnWrapURL

func UnWrapURL(r *http.Request) (map[string]any, error)

func Wrap

func Wrap(w http.ResponseWriter, data any, msg ...string) error

func ZeroTime

func ZeroTime(tm time.Time) time.Time

func ZeroTimestamp

func ZeroTimestamp(ts int64) int64

Types

type AESCrypter

type AESCrypter interface {
	Encrypt(keyString, plainString string) (string, error)
	Decrypt(keyString, cipherString string) (string, error)
}

func NewCTRCrypt

func NewCTRCrypt() AESCrypter

type ApiWrapper

type ApiWrapper struct {
	Code int    `json:"code"`
	Data any    `json:"data"`
	Msg  string `json:"msg"`
}

type AsyncError

type AsyncError struct {
	Err error
}

AsyncError is returned by FSM.Event() when a callback have initiated an asynchronous state transition.

func (AsyncError) Error

func (e AsyncError) Error() string

type CTRCrypt

type CTRCrypt struct{}

func (*CTRCrypt) Decrypt

func (*CTRCrypt) Decrypt(keyString, cipherString string) (string, error)

func (*CTRCrypt) Encrypt

func (*CTRCrypt) Encrypt(keyString, plainString string) (string, error)

type Callback

type Callback func(*Event)

type CallbackKey

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

type CallbackType

type CallbackType int
const (
	None CallbackType = iota
	BeforeEvent
	LeaveState
	EnterState
	AfterEvent
)

type Callbacks

type Callbacks map[string]Callback

type CanceledError

type CanceledError struct {
	Err error
}

CanceledError is returned by FSM.Event() when a callback have canceled a transition.

func (CanceledError) Error

func (e CanceledError) Error() string

type Event

type Event struct {
	FSM   *FSM
	Event EventType
	Src   StateType
	Dst   StateType
	Err   error
	Args  []interface{}
	// contains filtered or unexported fields
}

Event is the info that get passed as a reference in the callbacks.

type EventDesc

type EventDesc struct {
	Name EventType
	Src  []StateType
	Dst  StateType
}

type EventKey

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

type EventType

type EventType int

type FSM

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

func NewFSM

func NewFSM(initState StateType, events []EventDesc, callbacks map[CallbackKey]Callback) *FSM

func (*FSM) Current

func (fsm *FSM) Current() StateType

func (*FSM) Event

func (fsm *FSM) Event(eventType EventType, args ...any) error

func (*FSM) Is

func (fsm *FSM) Is(state StateType) bool

func (*FSM) Metadata

func (f *FSM) Metadata(key string) (any, bool)

func (*FSM) Previous

func (fsm *FSM) Previous() StateType

func (*FSM) Transition

func (fsm *FSM) Transition(event EventType)

type FSMManage

type FSMManage struct{}

type FileStorage

type FileStorage struct {
	BasePath string
	Date     string
}

func NewFileStorage

func NewFileStorage(basePath, date string) *FileStorage

func (*FileStorage) Append

func (fs *FileStorage) Append(name string, data any) error

func (*FileStorage) Save

func (fs *FileStorage) Save(name string, data []byte) error

type FullPasswordConf

type FullPasswordConf struct {
	Length          int
	NumLowerLetters int
	NumUpperLetters int
	NumDigits       int
	NumSymbols      int
}

func SetLevel

func SetLevel(level, length int) FullPasswordConf

type IFSM

type IFSM interface{}

type Ider

type Ider interface {
	NextInt64Id() int64
	NextStringId() string
}

func NewUUID

func NewUUID() Ider

func NewXId

func NewXId() Ider

func NewYitId

func NewYitId() Ider

type InTransitionError

type InTransitionError struct {
	Event string
}

InTransitionError is returned by FSM.Event() when an asynchronous transition is already in progress.

func (InTransitionError) Error

func (e InTransitionError) Error() string

type InternalError

type InternalError struct{}

InternalError is returned by FSM.Event() and should never occur. It is a probably because of a bug.

func (InternalError) Error

func (e InternalError) Error() string

type InvalidEventError

type InvalidEventError struct {
	Event string
	State string
}

InvalidEventError is returned by FSM.Event() when the event cannot be called in the current state.

func (InvalidEventError) Error

func (e InvalidEventError) Error() string

type JsonUnmarshal

type JsonUnmarshal struct{}

func (*JsonUnmarshal) ReadConfig

func (j *JsonUnmarshal) ReadConfig(p []byte, v any) error

func (*JsonUnmarshal) ReadConfigFromFile

func (j *JsonUnmarshal) ReadConfigFromFile(path string, v any) error

type LumberjackOption

type LumberjackOption func(*lumberjack.Logger)

func Compress

func Compress(b bool) LumberjackOption

func LocalTime

func LocalTime(b bool) LumberjackOption

func MaxAge

func MaxAge(i int) LumberjackOption

func MaxBackups

func MaxBackups(i int) LumberjackOption

func MaxSize

func MaxSize(i int) LumberjackOption

type Mail

type Mail struct {
	Auth smtp.Auth
	Host string
	Addr string
	From string
}

func (*Mail) SendMail

func (m *Mail) SendMail(subject, body string, to []string) error

type Mailer

type Mailer interface {
	SendMail(subject, body string, to []string) error
}

func NewMail

func NewMail(auth smtp.Auth, from, host string, port int) Mailer

type MariaDB

type MariaDB struct {
	// connAttempts int
	// connTimeout  time.Duration
	*sql.DB
}

func NewMaria

func NewMaria(dsn string, opts ...Option) (*MariaDB, error)

func (*MariaDB) Close

func (db *MariaDB) Close()

type NoTransitionError

type NoTransitionError struct {
	Err error
}

NoTransitionError is returned by FSM.Event() when no transition have happened, for example if the source and destination states are the same.

func (NoTransitionError) Error

func (e NoTransitionError) Error() string

type NotInTransitionError

type NotInTransitionError struct{}

NotInTransitionError is returned by FSM.Transition() when an asynchronous transition is not in progress.

func (NotInTransitionError) Error

func (e NotInTransitionError) Error() string

type Numbers

type Numbers interface {
	uint8 | uint16 | uint32 | uint64 | int8 | int16 | int32 | int64 | float32 | float64 | int | uint
}

type Option

type Option func(*sql.DB)

func ConnMaxIdleTime

func ConnMaxIdleTime(d time.Duration) Option

ConnMaxIdleTime 一个连接空闲的最大时长

func ConnMaxLifetime

func ConnMaxLifetime(d time.Duration) Option

ConnMaxLifetime 一个连接使用的最大时长

func MaxIdleConns

func MaxIdleConns(size int) Option

MaxIdleConns 最大闲置的连接数

func MaxOpenConns

func MaxOpenConns(size int) Option

MaxOpenConns 最大打开的连接数

type Postgres

type Postgres struct {
	*sql.DB
}

func NewPostgres

func NewPostgres(dsn string, opts ...Option) (*Postgres, error)

func (*Postgres) Close

func (db *Postgres) Close()

type Pretty

type Pretty interface {
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
	Prepare(query string) (*sql.Stmt, error)
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	Exec(query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	Query(query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
	QueryRow(query string, args ...any) *sql.Row
}

type PrettyDB

type PrettyDB interface {
	Pretty
	BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
	Begin() (*sql.Tx, error)
}

func NewMariaDB

func NewMariaDB() PrettyDB

func NewPostgresDB

func NewPostgresDB() PrettyDB

type PrettyTx

type PrettyTx interface {
	Pretty
	Commit() error
	Rollback() error
	StmtContext(ctx context.Context, stmt *sql.Stmt) *sql.Stmt
	Stmt(stmt *sql.Stmt) *sql.Stmt
}

func NewMariaTx

func NewMariaTx() (PrettyTx, error)

func NewMariaTxContext

func NewMariaTxContext(ctx context.Context) (PrettyTx, error)

func NewPostgresTx

func NewPostgresTx() (PrettyTx, error)

func NewPostgresTxContext

func NewPostgresTxContext(ctx context.Context) (PrettyTx, error)

type RSASign

type RSASign struct {
	PrivateKey *rsa.PrivateKey
	PublicKey  *rsa.PublicKey
}

func (*RSASign) Sign

func (r *RSASign) Sign(data []byte) ([]byte, error)

func (*RSASign) Verify

func (r *RSASign) Verify(data []byte, signature []byte) error

type Redis

type Redis struct{ *redis.Client }

func NewRedis

func NewRedis(addr string, opts ...RedisOption) (*Redis, error)

func NewRedisDB

func NewRedisDB() *Redis

type RedisOption

type RedisOption func(*redis.Options)

func RedisAddr

func RedisAddr(addr string) RedisOption

func RedisDB

func RedisDB(db int) RedisOption

func RedisPassword

func RedisPassword(pwd string) RedisOption

func RedisPoolSize

func RedisPoolSize(poolSize int) RedisOption

type Server

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

Server -.

func NewHttpServer

func NewHttpServer(handler http.Handler, opts ...ServerOption) *Server

NewHttpServer -.

func (*Server) Notify

func (s *Server) Notify() <-chan error

Notify -.

func (*Server) Shutdown

func (s *Server) Shutdown() error

Shutdown -.

type ServerOption

type ServerOption func(*Server)

ServerOption -.

func Port

func Port(port string) ServerOption

Port -.

func ReadTimeout

func ReadTimeout(timeout time.Duration) ServerOption

ReadTimeout -.

func ShutdownTimeout

func ShutdownTimeout(timeout time.Duration) ServerOption

ShutdownTimeout -.

func WriteTimeout

func WriteTimeout(timeout time.Duration) ServerOption

WriteTimeout -.

type Signer

type Signer interface {
	Sign(data []byte) ([]byte, error)
	Verify(data []byte, signature []byte) error
}

func NewRSASignFromBytes

func NewRSASignFromBytes(privateKeyData, publicKeyData []byte) (Signer, error)

func NewRSASignFromFile

func NewRSASignFromFile(privateKeyFile, publicKeyFile string) (Signer, error)

type StateType

type StateType int

type Storage

type Storage interface {
	Save(name string, data []byte) error
	Append(name string, data any) error
}

type Task

type Task func() error

type TaskContext

type TaskContext func(ctx context.Context) error

type TomlUnmarshal

type TomlUnmarshal struct{}

func (*TomlUnmarshal) ReadConfig

func (t *TomlUnmarshal) ReadConfig(p []byte, v any) error

func (*TomlUnmarshal) ReadConfigFromFile

func (t *TomlUnmarshal) ReadConfigFromFile(path string, v any) error

type Transition

type Transition int

type UUID

type UUID struct{}

func (*UUID) NextInt64Id

func (u *UUID) NextInt64Id() int64

func (*UUID) NextStringId

func (u *UUID) NextStringId() string

type UnknownEventError

type UnknownEventError struct {
	Event string
}

UnknownEventError is returned by FSM.Event() when the event is not defined.

func (UnknownEventError) Error

func (e UnknownEventError) Error() string

type UnmarshalConfiger

type UnmarshalConfiger interface {
	ReadConfig(p []byte, v any) error
	ReadConfigFromFile(path string, v any) error
}

func NewJsonUnmarshal

func NewJsonUnmarshal() UnmarshalConfiger

func NewTomlUnmarshal

func NewTomlUnmarshal() UnmarshalConfiger

func NewYamlUnmarshal

func NewYamlUnmarshal() UnmarshalConfiger

type XId

type XId struct{}

func (*XId) NextInt64Id

func (x *XId) NextInt64Id() int64

func (*XId) NextStringId

func (x *XId) NextStringId() string

type YamlUnmarshal

type YamlUnmarshal struct{}

func (*YamlUnmarshal) ReadConfig

func (y *YamlUnmarshal) ReadConfig(p []byte, v any) error

func (*YamlUnmarshal) ReadConfigFromFile

func (y *YamlUnmarshal) ReadConfigFromFile(path string, v any) error

type YitId

type YitId struct{}

func (*YitId) NextInt64Id

func (n *YitId) NextInt64Id() int64

func (*YitId) NextStringId

func (n *YitId) NextStringId() string

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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