yiigo

package module
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2021 License: Apache-2.0 Imports: 50 Imported by: 0

README

yiigo

golang GitHub release pkg.go.dev Apache 2.0 license

一个好用的 Go 轻量级开发通用库,省去你到处找库封装的烦恼,让 Go 开发更加简单快捷

Features

  • 支持 MySQL
  • 支持 PostgreSQL
  • 支持 SQLite3
  • 支持 MongoDB
  • 支持 Redis
  • 支持 NSQ
  • SQL使用 sqlx
  • ORM推荐 ent
  • 日志使用 zap
  • gRPC Client 连接池
  • 轻量的 SQL Builder
  • 环境配置使用 dotenv,支持热加载
  • 实用的辅助方法,包含:http、cypto、date、IP、version compare 等

Requirements

Go1.15+

Installation

go get -u github.com/shenghui0779/yiigo

Usage

ENV
  • load
// 默认加载当前目录下的`.env`文件
yiigo.LoadEnv()

// 加载指定文件
yiigo.LoadEnv(yiigo.WithEnvFile("mycfg.env"))

// 热加载
yiigo.LoadEnv(yiigo.WithEnvWatcher(onchanges...))
  • .env
ENV=dev
  • usage
fmt.Println(os.Getenv("ENV"))
// output: dev
DB
  • register
yiigo.Init(
    yiigo.WithDB(yiigo.Default, yiigo.MySQL, "dsn", options...),
    yiigo.WithDB("other", yiigo.MySQL, "dsn", options...),
)
  • sqlx
// default db
yiigo.DB().Get(&User{}, "SELECT * FROM user WHERE id = ?", 1)

// other db
yiigo.DB("other").Get(&User{}, "SELECT * FROM user WHERE id = ?", 1)
  • ent
import "<your_project>/ent"

// default driver
client := ent.NewClient(ent.Driver(yiigo.EntDriver()))

// other driver
client := ent.NewClient(ent.Driver(yiigo.EntDriver("other")))
MongoDB
// register
yiigo.Init(
    yiigo.WithMongo(yiigo.Default, "dsn"),
    yiigo.WithMongo("other", "dsn"),
)

// default mongodb
yiigo.Mongo().Database("test").Collection("numbers").InsertOne(context.Background(), bson.M{"name": "pi", "value": 3.14159})

// other mongodb
yiigo.Mongo("other").Database("test").Collection("numbers").InsertOne(context.Background(), bson.M{"name": "pi", "value": 3.14159})
Redis
// register
yiigo.Init(
    yiigo.WithRedis(yiigo.Default, "address", options...),
    yiigo.WithRedis("other", "address", options...),
)

// default redis
conn, err := yiigo.Redis().Get(context.Background())

if err != nil {
    log.Fatal(err)
}

defer yiigo.Redis().Put(conn)

conn.Do("SET", "test_key", "hello world")

// other redis
conn, err := yiigo.Redis("other").Get(context.Background())

if err != nil {
    log.Fatal(err)
}

defer yiigo.Redis("other").Put(conn)

conn.Do("SET", "test_key", "hello world")
Logger
// register
yiigo.Init(
    yiigo.WithLogger(yiigo.Default, "filepath", options...),
    yiigo.WithLogger("other", "filepath", options...),
)

// default logger
yiigo.Logger().Info("hello world")

// other logger
yiigo.Logger("other").Info("hello world")
gRPC Pool
// create pool
pool := yiigo.NewGRPCPool(
    func() (*grpc.ClientConn, error) {
        return grpc.DialContext(context.Background(), "target",
            grpc.WithInsecure(),
            grpc.WithBlock(),
            grpc.WithKeepaliveParams(keepalive.ClientParameters{
                Time:    time.Second * 30,
                Timeout: time.Second * 10,
            }),
        )
    },
    yiigo.WithPoolSize(10),
    yiigo.WithPoolLimit(20),
    yiigo.WithPoolIdleTimeout(600*time.Second),
)

// use pool
conn, err := pool.Get(context.Background())

if err != nil {
    return err
}

defer pool.Put(conn)

// coding...
HTTP
// default client
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
yiigo.HTTPGet(ctx, "URL")

// new client
client := yiigo.NewHTTPClient(*http.Client)

ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
client.Do(ctx, http.MethodGet, "URL", nil)
SQL Builder

😊 为不想手写SQL的你生成SQL语句,用于 sqlx 的相关方法;

⚠️ 作为辅助方法,目前支持的特性有限,复杂的SQL(如:子查询等)还需自己手写

builder := yiigo.NewMySQLBuilder()
// builder := yiigo.NewSQLBuilder(yiigo.MySQL)
  • Query
builder.Wrap(
    yiigo.Table("user"),
    yiigo.Where("id = ?", 1),
).ToQuery()
// SELECT * FROM user WHERE id = ?
// [1]

builder.Wrap(
    yiigo.Table("user"),
    yiigo.Where("name = ? AND age > ?", "shenghui0779", 20),
).ToQuery()
// SELECT * FROM user WHERE name = ? AND age > ?
// [shenghui0779 20]

builder.Wrap(
    yiigo.Table("user"),
    yiigo.WhereIn("age IN (?)", []int{20, 30}),
).ToQuery()
// SELECT * FROM user WHERE age IN (?, ?)
// [20 30]

builder.Wrap(
    yiigo.Table("user"),
    yiigo.Select("id", "name", "age"),
    yiigo.Where("id = ?", 1),
).ToQuery()
// SELECT id, name, age FROM user WHERE id = ?
// [1]

builder.Wrap(
    yiigo.Table("user"),
    yiigo.Distinct("name"),
    yiigo.Where("id = ?", 1),
).ToQuery()
// SELECT DISTINCT name FROM user WHERE id = ?
// [1]

builder.Wrap(
    yiigo.Table("user"),
    yiigo.LeftJoin("address", "user.id = address.user_id"),
    yiigo.Where("user.id = ?", 1),
).ToQuery()
// SELECT * FROM user LEFT JOIN address ON user.id = address.user_id WHERE user.id = ?
// [1]

builder.Wrap(
    yiigo.Table("address"),
    yiigo.Select("user_id", "COUNT(*) AS total"),
    yiigo.GroupBy("user_id"),
    yiigo.Having("user_id = ?", 1),
).ToQuery()
// SELECT user_id, COUNT(*) AS total FROM address GROUP BY user_id HAVING user_id = ?
// [1]

builder.Wrap(
    yiigo.Table("user"),
    yiigo.Where("age > ?", 20),
    yiigo.OrderBy("age ASC", "id DESC"),
    yiigo.Offset(5),
    yiigo.Limit(10),
).ToQuery()
// SELECT * FROM user WHERE age > ? ORDER BY age ASC, id DESC LIMIT ? OFFSET ?
// [20, 10, 5]

wrap1 := builder.Wrap(
    Table("user_1"),
    Where("id = ?", 2),
)

builder.Wrap(
    Table("user_0"),
    Where("id = ?", 1),
    Union(wrap1),
).ToQuery()
// (SELECT * FROM user_0 WHERE id = ?) UNION (SELECT * FROM user_1 WHERE id = ?)
// [1, 2]

builder.Wrap(
    Table("user_0"),
    Where("id = ?", 1),
    UnionAll(wrap1),
).ToQuery()
// (SELECT * FROM user_0 WHERE id = ?) UNION ALL (SELECT * FROM user_1 WHERE id = ?)
// [1, 2]

builder.Wrap(
    Table("user_0"),
    WhereIn("age IN (?)", []int{10, 20}),
    Limit(5),
    Union(
        builder.Wrap(
            Table("user_1"),
            Where("age IN (?)", []int{30, 40}),
            Limit(5),
        ),
    ),
).ToQuery()
// (SELECT * FROM user_0 WHERE age IN (?, ?) LIMIT ?) UNION (SELECT * FROM user_1 WHERE age IN (?, ?) LIMIT ?)
// [10, 20, 5, 30, 40, 5]

builder.Wrap(Table("user")).ToTruncate()
// TRUNCATE user
  • Insert
type User struct {
    ID     int    `db:"-"`
    Name   string `db:"name"`
    Age    int    `db:"age"`
    Phone  string `db:"phone,omitempty"`
}

builder.Wrap(Table("user")).ToInsert(&User{
    Name: "yiigo",
    Age:  29,
})
// INSERT INTO user (name, age) VALUES (?, ?)
// [yiigo 29]

builder.Wrap(yiigo.Table("user")).ToInsert(yiigo.X{
    "name": "yiigo",
    "age":  29,
})
// INSERT INTO user (name, age) VALUES (?, ?)
// [yiigo 29]
  • Batch Insert
type User struct {
    ID     int    `db:"-"`
    Name   string `db:"name"`
    Age    int    `db:"age"`
    Phone  string `db:"phone,omitempty"`
}

builder.Wrap(Table("user")).ToBatchInsert([]*User{
    {
        Name: "shenghui0779",
        Age:  20,
    },
    {
        Name: "yiigo",
        Age:  29,
    },
})
// INSERT INTO user (name, age) VALUES (?, ?), (?, ?)
// [shenghui0779 20 yiigo 29]

builder.Wrap(yiigo.Table("user")).ToBatchInsert([]yiigo.X{
    {
        "name": "shenghui0779",
        "age":  20,
    },
    {
        "name": "yiigo",
        "age":  29,
    },
})
// INSERT INTO user (name, age) VALUES (?, ?), (?, ?)
// [shenghui0779 20 yiigo 29]
  • Update
type User struct {
    Name   string `db:"name"`
    Age    int    `db:"age"`
    Phone  string `db:"phone,omitempty"`
}

builder.Wrap(
    Table("user"),
    Where("id = ?", 1),
).ToUpdate(&User{
    Name: "yiigo",
    Age:  29,
})
// UPDATE user SET name = ?, age = ? WHERE id = ?
// [yiigo 29 1]

builder.Wrap(
    yiigo.Table("user"),
    yiigo.Where("id = ?", 1),
).ToUpdate(yiigo.X{
    "name": "yiigo",
    "age":  29,
})
// UPDATE user SET name = ?, age = ? WHERE id = ?
// [yiigo 29 1]

builder.Wrap(
    yiigo.Table("product"),
    yiigo.Where("id = ?", 1),
).ToUpdate(yiigo.X{
    "price": yiigo.Clause("price * ? + ?", 2, 100),
})
// UPDATE product SET price = price * ? + ? WHERE id = ?
// [2 100 1]
  • Delete
builder.Wrap(
    yiigo.Table("user"),
    yiigo.Where("id = ?", 1),
).ToDelete()
// DELETE FROM user WHERE id = ?
// [1]

Documentation

Enjoy 😊

Documentation

Index

Constants

View Source
const Default = "default"

Default defines for `default` name

Variables

This section is empty.

Functions

func AddSlashes

func AddSlashes(s string) string

AddSlashes returns a string with backslashes added before characters that need to be escaped.

func Date

func Date(timestamp int64, layout ...string) string

Date format a local time/date and returns a string formatted according to the given format string using the given timestamp of int64. The default layout is: 2006-01-02 15:04:05.

func Float64sUnique

func Float64sUnique(a []float64) []float64

Float64sUnique takes an input slice of float64s and returns a new slice of float64s without duplicate values.

func GenerateRSAKey

func GenerateRSAKey(bitSize int, blockType PemBlockType) (privateKey, publicKey []byte, err error)

GenerateRSAKey returns rsa private and public key.

func HMAC

func HMAC(algo HashAlgo, s, key string) string

HMAC generates a keyed hash value, expects: MD5, SHA1, SHA224, SHA256, SHA384, SHA512.

func HTTPDo

func HTTPDo(ctx context.Context, method, reqURL string, body io.Reader, options ...HTTPOption) (*http.Response, error)

HTTPDo sends an HTTP request and returns an HTTP response

func HTTPGet

func HTTPGet(ctx context.Context, reqURL string, options ...HTTPOption) (*http.Response, error)

HTTPGet issues a GET to the specified URL.

func HTTPPost

func HTTPPost(ctx context.Context, reqURL string, body []byte, options ...HTTPOption) (*http.Response, error)

HTTPPost issues a POST to the specified URL.

func HTTPPostForm

func HTTPPostForm(ctx context.Context, reqURL string, data url.Values, options ...HTTPOption) (*http.Response, error)

HTTPPostForm issues a POST to the specified URL, with data's keys and values URL-encoded as the request body.

func HTTPUpload

func HTTPUpload(ctx context.Context, reqURL string, form UploadForm, options ...HTTPOption) (*http.Response, error)

HTTPUpload issues a UPLOAD to the specified URL.

func Hash

func Hash(algo HashAlgo, s string) string

Hash generates a hash value, expects: MD5, SHA1, SHA224, SHA256, SHA384, SHA512.

func IP2Long

func IP2Long(ip string) uint32

IP2Long converts a string containing an (IPv4) Internet Protocol dotted address into an uint32 integer.

func InArray

func InArray(needle interface{}, haystack []interface{}) bool

InArray checks if a value of interface{} exists in a slice of []interface{}.

func InFloat64s

func InFloat64s(needle float64, haystack []float64) bool

InFloat64s checks if a value of float64 exists in a slice of []float64.

func InInt64s

func InInt64s(needle int64, haystack []int64) bool

InInt64s checks if a value of int64 exists in a slice of []int64.

func InInts

func InInts(needle int, haystack []int) bool

InInts checks if a value of int exists in a slice of []int.

func InStrings

func InStrings(needle string, haystack []string) bool

InStrings checks if a value of string exists in a slice of []string.

func Init

func Init(options ...InitOption)

Init yiigo initialization.

func Int64sUnique

func Int64sUnique(a []int64) []int64

Int64sUnique takes an input slice of int64s and returns a new slice of int64s without duplicate values.

func IntsUnique

func IntsUnique(a []int) []int

IntsUnique takes an input slice of ints and returns a new slice of ints without duplicate values.

func LoadEnv

func LoadEnv(options ...EnvOption) error

LoadEnv will read your env file(s) and load them into ENV for this process. It will default to loading .env in the current path if not specifies the filename.

func Logger

func Logger(name ...string) *zap.Logger

Logger returns a logger

func Long2IP

func Long2IP(ip uint32) string

Long2IP converts an uint32 integer address into a string in (IPv4) Internet standard dotted format.

func MD5

func MD5(s string) string

MD5 calculates the md5 hash of a string.

func Mongo

func Mongo(name ...string) *mongo.Client

Mongo returns a mongo client.

func MyTimeEncoder

func MyTimeEncoder(t time.Time, e zapcore.PrimitiveArrayEncoder)

MyTimeEncoder zap time encoder.

func NSQDeferredPublish

func NSQDeferredPublish(topic string, msg NSQMessage, duration time.Duration) error

NSQDeferredPublish synchronously publishes a message body to the specified topic where the message will queue at the channel level until the timeout expires.

func NSQPublish

func NSQPublish(topic string, msg NSQMessage) error

NSQPublish synchronously publishes a message body to the specified topic.

func NewECBDecrypter

func NewECBDecrypter(b cipher.Block) cipher.BlockMode

NewECBDecrypter returns a BlockMode which decrypts in electronic code book mode, using the given Block.

func NewECBEncrypter

func NewECBEncrypter(b cipher.Block) cipher.BlockMode

NewECBEncrypter returns a BlockMode which encrypts in electronic code book mode, using the given Block.

func NextAttemptDuration

func NextAttemptDuration(attempts uint16) time.Duration

NextAttemptDuration helper for attempt duration.

func PKCS5Padding

func PKCS5Padding(cipherText []byte, blockSize int) []byte

func PKCS5Unpadding

func PKCS5Unpadding(plainText []byte, blockSize int) []byte

func QuoteMeta

func QuoteMeta(s string) string

QuoteMeta returns a version of str with a backslash character (\) before every character that is among these: . \ + * ? [ ^ ] ( $ )

func RSADecrypt

func RSADecrypt(cipherText, privateKey []byte) ([]byte, error)

RSADecrypt rsa decrypt with PKCS #1 v1.5

func RSADecryptOEAP

func RSADecryptOEAP(cipherText, privateKey []byte) ([]byte, error)

RSADecryptOEAP rsa decrypt with PKCS #1 OEAP.

func RSAEncrypt

func RSAEncrypt(plainText, publicKey []byte) ([]byte, error)

RSAEncrypt rsa encrypt with PKCS #1 v1.5

func RSAEncryptOEAP

func RSAEncryptOEAP(plainText, publicKey []byte) ([]byte, error)

RSAEncryptOEAP rsa encrypt with PKCS #1 OEAP.

func RSAPemToSSH

func RSAPemToSSH(pemPubKey []byte) (sshRSA []byte, fingerprint string, err error)

RSAPemToSSH converts rsa public key from pem to ssh-rsa. Note: value ends with `\n`

func RSASignWithSha256

func RSASignWithSha256(data, privateKey []byte) ([]byte, error)

RSASignWithSha256 returns rsa signature with sha256.

func RSAVerifyWithSha256

func RSAVerifyWithSha256(data, signature, publicKey []byte) error

RSAVerifyWithSha256 verifies rsa signature with sha256.

func SHA1

func SHA1(s string) string

SHA1 calculates the sha1 hash of a string.

func SearchInt64s

func SearchInt64s(a []int64, x int64) int

SearchInt64s searches for x in a sorted slice of int64s and returns the index as specified by Search. The return value is the index to insert x if x is not present (it could be len(a)). The slice must be sorted in ascending order.

func SortInt64s

func SortInt64s(a []int64)

SortInt64s sorts []int64s in increasing order.

func StrToTime

func StrToTime(datetime string, layout ...string) int64

StrToTime Parse English textual datetime description into a Unix timestamp. The default layout is: 2006-01-02 15:04:05.

func StringsUnique

func StringsUnique(a []string) []string

StringsUnique takes an input slice of strings and returns a new slice of strings without duplicate values.

func StripSlashes

func StripSlashes(s string) string

StripSlashes returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\).

func VersionCompare

func VersionCompare(rangeVer, curVer string) (bool, error)

VersionCompare compares semantic versions range, support: >, >=, =, !=, <, <=, | (or), & (and). Param `rangeVer` eg: 1.0.0, =1.0.0, >2.0.0, >=1.0.0&<2.0.0, <2.0.0|>3.0.0, !=4.0.4

func WeekAround

func WeekAround(t time.Time) (monday, sunday string)

WeekAround returns the date of monday and sunday for current week.

func ZeroPadding

func ZeroPadding(cipherText []byte, blockSize int) []byte

func ZeroUnPadding

func ZeroUnPadding(plainText []byte) []byte

Types

type AESCrypto

type AESCrypto interface {
	// Encrypt encrypts the plain text.
	Encrypt(plainText []byte) ([]byte, error)

	// Decrypt decrypts the cipher text.
	Decrypt(cipherText []byte) ([]byte, error)
}

AESCrypto is the interface for aes crypto.

func NewCBCCrypto

func NewCBCCrypto(key, iv []byte, mode PaddingMode) AESCrypto

NewCBCCrypto returns a new aes-cbc crypto.

func NewCFBCrypto

func NewCFBCrypto(key, iv []byte) AESCrypto

NewCFBCrypto returns a new aes-cfb crypto

func NewCTRCrypto

func NewCTRCrypto(key, iv []byte) AESCrypto

NewCTRCrypto returns a new aes-ctr crypto

func NewECBCrypto

func NewECBCrypto(key []byte, mode PaddingMode) AESCrypto

NewECBCrypto returns a new aes-ecb crypto.

func NewGCMCrypto

func NewGCMCrypto(key, nonce []byte) AESCrypto

NewGCMCrypto returns a new aes-gcm crypto

func NewOFBCrypto

func NewOFBCrypto(key, iv []byte) AESCrypto

NewOFBCrypto returns a new aes-ofb crypto

type CDATA

type CDATA string

CDATA XML CDATA section which is defined as blocks of text that are not parsed by the parser, but are otherwise recognized as markup.

func (CDATA) MarshalXML

func (c CDATA) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML encodes the receiver as zero or more XML elements.

type EnvEventFunc

type EnvEventFunc func(event fsnotify.Event)

EnvEventFunc the function that runs each time env change occurs.

type EnvOption

type EnvOption func(e *environment)

EnvOption configures how we set up env file.

func WithEnvFile

func WithEnvFile(filename string) EnvOption

WithEnvFile specifies the env file.

func WithEnvWatcher

func WithEnvWatcher(fn ...EnvEventFunc) EnvOption

WithEnvWatcher watching and re-reading env file.

type GRPCConn

type GRPCConn struct {
	*grpc.ClientConn
}

GRPCConn grpc connection resource

func (*GRPCConn) Close

func (gc *GRPCConn) Close()

Close closes the connection resource

type GRPCDialFunc

type GRPCDialFunc func() (*grpc.ClientConn, error)

GRPCDialFunc grpc dial function

type GRPCPool

type GRPCPool interface {
	// Get returns a connection resource from the pool.
	// Context with timeout can specify the wait timeout for pool.
	Get(ctx context.Context) (*GRPCConn, error)

	// Put returns a connection resource to the pool.
	Put(gc *GRPCConn)
}

GRPCPool grpc pool resource

func NewGRPCPool

func NewGRPCPool(dial GRPCDialFunc, options ...PoolOption) GRPCPool

NewGRPCPool returns a new grpc pool with dial func.

type HTTPClient

type HTTPClient interface {
	// Do sends an HTTP request and returns an HTTP response.
	// Should use context to specify the timeout for request.
	Do(ctx context.Context, method, reqURL string, body io.Reader, options ...HTTPOption) (*http.Response, error)

	// Upload issues a UPLOAD to the specified URL.
	// Should use context to specify the timeout for request.
	Upload(ctx context.Context, reqURL string, form UploadForm, options ...HTTPOption) (*http.Response, error)
}

HTTPClient is the interface for a http client.

func NewHTTPClient

func NewHTTPClient(client *http.Client) HTTPClient

NewHTTPClient returns a new http client

type HTTPOption

type HTTPOption func(s *httpSetting)

HTTPOption configures how we set up the http request.

func WithHTTPClose

func WithHTTPClose() HTTPOption

WithHTTPClose specifies close the connection after replying to this request (for servers) or after sending this request and reading its response (for clients).

func WithHTTPCookies

func WithHTTPCookies(cookies ...*http.Cookie) HTTPOption

WithHTTPCookies specifies the cookies to http request.

func WithHTTPHeader

func WithHTTPHeader(key, value string) HTTPOption

WithHTTPHeader specifies the header to http request.

type HashAlgo

type HashAlgo string

HashAlgo hash algorithm

const (
	AlgoMD5    HashAlgo = "md5"
	AlgoSha1   HashAlgo = "sha1"
	AlgoSha224 HashAlgo = "sha224"
	AlgoSha256 HashAlgo = "sha256"
	AlgoSha384 HashAlgo = "sha384"
	AlgoSha512 HashAlgo = "sha512"
)

type InitOption

type InitOption func(s *initSetting)

InitOption configures how we set up the yiigo initialization.

func WithLogger

func WithLogger(name, logfile string, options ...LoggerOption) InitOption

WithLogger register logger.

func WithMongo

func WithMongo(name string, dsn string) InitOption

WithMongo register mongodb. [DSN] mongodb://localhost:27017/?connectTimeoutMS=10000&minPoolSize=10&maxPoolSize=20&maxIdleTimeMS=60000&readPreference=primary [reference] https://docs.mongodb.com/manual/reference/connection-string

func WithNSQ

func WithNSQ(nsqd string, lookupd []string, options ...NSQOption) InitOption

WithNSQ initialize the nsq.

func WithRedis

func WithRedis(name, address string, options ...RedisOption) InitOption

WithRedis register redis.

type Int64Slice

type Int64Slice []int64

Int64Slice attaches the methods of Interface to []int64, sorting a increasing order.

func (Int64Slice) Len

func (p Int64Slice) Len() int

func (Int64Slice) Less

func (p Int64Slice) Less(i, j int) bool

func (Int64Slice) Swap

func (p Int64Slice) Swap(i, j int)

type LoggerOption

type LoggerOption func(s *loggerSetting)

LoggerOption configures how we set up the logger.

func WithLogCompress

func WithLogCompress() LoggerOption

WithLogCompress specifies the `Compress` for logger.

func WithLogMaxAge

func WithLogMaxAge(n int) LoggerOption

WithLogMaxAge specifies the `MaxAge(days)` for logger.

func WithLogMaxBackups

func WithLogMaxBackups(n int) LoggerOption

WithLogMaxBackups specifies the `MaxBackups` for logger.

func WithLogMaxSize

func WithLogMaxSize(n int) LoggerOption

WithLogMaxSize specifies the `MaxSize(Mi)` for logger.

func WithLogStdErr

func WithLogStdErr() LoggerOption

WithLogStdErr specifies stderr output for logger.

type NSQConsumer

type NSQConsumer interface {
	nsq.Handler
	Topic() string
	Channel() string
	AttemptCount() uint16
}

NSQConsumer NSQ consumer

type NSQLogger

type NSQLogger struct{}

NSQLogger NSQ logger

func (*NSQLogger) Output

func (l *NSQLogger) Output(calldepth int, s string) error

Output implements the NSQ logger interface

type NSQMessage

type NSQMessage interface {
	Bytes() ([]byte, error)
	// Do message processing
	Do() error
}

NSQMessage NSQ message

type NSQOption

type NSQOption func(s *nsqSetting)

NSQOption configures how we set up the nsq config.

func WithLookupdPollInterval

func WithLookupdPollInterval(t time.Duration) NSQOption

WithLookupdPollInterval specifies the `LookupdPollInterval` for nsq config.

func WithMaxInFlight

func WithMaxInFlight(n int) NSQOption

WithMaxInFlight specifies the `MaxInFlight` for nsq config.

func WithNSQConsumer

func WithNSQConsumer(consumer NSQConsumer) NSQOption

WithNSQConsumer specifies the consumer for nsq.

func WithRDYRedistributeInterval

func WithRDYRedistributeInterval(t time.Duration) NSQOption

WithRDYRedistributeInterval specifies the `RDYRedistributeInterval` for nsq config.

type PaddingMode

type PaddingMode string

PaddingMode aes padding mode

const (
	// ZERO zero padding mode
	ZERO PaddingMode = "ZERO"
	// PKCS5 PKCS#5 padding mode
	PKCS5 PaddingMode = "PKCS#5"
	// PKCS7 PKCS#7 padding mode
	PKCS7 PaddingMode = "PKCS#7"
)

type PemBlockType

type PemBlockType string

PemBlockType pem block type which taken from the preamble.

const (
	// RSAPKCS1 private key in PKCS#1
	RSAPKCS1 PemBlockType = "RSA PRIVATE KEY"
	// RSAPKCS8 private key in PKCS#8
	RSAPKCS8 PemBlockType = "PRIVATE KEY"
)

type PoolOption

type PoolOption func(s *poolSetting)

PoolOption configures how we set up the pool.

func WithPoolIdleTimeout

func WithPoolIdleTimeout(duration time.Duration) PoolOption

WithPoolIdleTimeout specifies the maximum amount of time a connection may be idle. An idleTimeout of 0 means that there is no timeout.

func WithPoolLimit

func WithPoolLimit(limit int) PoolOption

WithPoolLimit specifies the extent to which the pool can be resized in the future. You cannot resize the pool beyond poolLimit.

func WithPoolPrefill

func WithPoolPrefill(prefill int) PoolOption

WithPoolPrefill specifies how many resources can be opened in parallel.

func WithPoolSize

func WithPoolSize(size int) PoolOption

WithPoolSize specifies the number of possible resources in the pool.

type RedisConn

type RedisConn struct {
	redis.Conn
}

RedisConn redis connection resource

func (*RedisConn) Close

func (rc *RedisConn) Close()

Close closes the connection resource

type RedisOption

type RedisOption func(s *redisSetting)

RedisOption configures how we set up the redis.

func WithRedisConnTimeout

func WithRedisConnTimeout(t time.Duration) RedisOption

WithRedisConnTimeout specifies the `ConnectTimeout` for redis.

func WithRedisDatabase

func WithRedisDatabase(db int) RedisOption

WithRedisDatabase specifies the database for redis.

func WithRedisPool

func WithRedisPool(options ...PoolOption) RedisOption

WithRedisPool specifies the pool for redis.

func WithRedisReadTimeout

func WithRedisReadTimeout(t time.Duration) RedisOption

WithRedisReadTimeout specifies the `ReadTimeout` for redis.

func WithRedisWriteTimeout

func WithRedisWriteTimeout(t time.Duration) RedisOption

WithRedisWriteTimeout specifies the `WriteTimeout` for redis.

type RedisPool

type RedisPool interface {
	// Get returns a connection resource from the pool.
	// Context with timeout can specify the wait timeout for pool.
	Get(ctx context.Context) (*RedisConn, error)

	// Put returns a connection resource to the pool.
	Put(rc *RedisConn)
}

RedisPool redis pool resource

func Redis

func Redis(name ...string) RedisPool

Redis returns a redis pool.

type SSHKey

type SSHKey struct {
	IDRSA       []byte
	IDRSAPub    []byte
	Fingerprint string
}

func GenerateSSHKey

func GenerateSSHKey() (*SSHKey, error)

GenerateSSHKey returns ssh id_rsa and id_rsa.pub. Note: id_rsa.pub ends with `\n`

type UploadField

type UploadField func(f *uploadform)

UploadField configures how we set up the upload from.

func WithFileField

func WithFileField(fieldname, filename string, body []byte) UploadField

WithFileField specifies the file field to upload from.

func WithFormField

func WithFormField(fieldname, fieldvalue string) UploadField

WithFormField specifies the form field to upload from.

type UploadForm

type UploadForm interface {
	// Write writes fields to multipart writer
	Write(w *multipart.Writer) error
}

UploadForm is the interface for http upload

func NewUploadForm

func NewUploadForm(fields ...UploadField) UploadForm

NewUploadForm returns an upload form

type Validator

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

Validator a validator which can be used for Gin.

func NewValidator

func NewValidator() *Validator

NewValidator returns a new validator. Used for Gin: binding.Validator = yiigo.NewValidator()

func (*Validator) Engine

func (v *Validator) Engine() interface{}

Engine returns the underlying validator engine which powers the default Validator instance. This is useful if you want to register custom validations or struct level validations. See validator GoDoc for more info - https://godoc.org/gopkg.in/go-playground/validator.v10

func (*Validator) ValidateStruct

func (v *Validator) ValidateStruct(obj interface{}) error

ValidateStruct receives any kind of type, but only performed struct or pointer to struct type.

type X

type X map[string]interface{}

X is a convenient alias for a map[string]interface{}.

Jump to

Keyboard shortcuts

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