# README
yiigo
A simple and light library which makes Golang development easier !
Features
- Support MySQL
- Support PostgreSQL
- Support MongoDB
- Support Redis
- Support Zipkin
- Use gomail for email sending
- Use toml for configuration
- Use sqlx for SQL executing
- Use gorm for ORM operating
- Use zap for logging
Requirements
Go1.11+
Installation
go get github.com/iiinsomnia/yiigo/v3
Usage
MySQL
// default db
yiigo.RegisterDB(yiigo.AsDefault, yiigo.MySQL, "root:root@tcp(localhost:3306)/test")
yiigo.DB().Get(&User{}, "SELECT * FROM `user` WHERE `id` = ?", 1)
yiigo.Orm().First(&User{}, 1)
// other db
yiigo.RegisterDB("foo", yiigo.MySQL, "root:root@tcp(localhost:3306)/foo")
yiigo.DB("foo").Get(&User{}, "SELECT * FROM `user` WHERE `id` = ?", 1)
yiigo.Orm("foo").First(&User{}, 1)
MongoDB
// default mongodb
yiigo.RegisterMongoDB(yiigo.AsDefault, "mongodb://localhost:27017")
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
yiigo.Mongo().Database("test").Collection("numbers").InsertOne(ctx, bson.M{"name": "pi", "value": 3.14159})
// other mongodb
yiigo.RegisterMongoDB("foo", "mongodb://localhost:27017")
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
yiigo.Mongo("foo").Database("test").Collection("numbers").InsertOne(ctx, bson.M{"name": "pi", "value": 3.14159})
Redis
// default redis
yiigo.RegisterRedis(yiigo.AsDefault, "localhost:6379")
conn, err := yiigo.Redis().Get()
if err != nil {
log.Fatal(err)
}
defer yiigo.Redis().Put(conn)
conn.Do("SET", "test_key", "hello world")
// other redis
yiigo.RegisterRedis("foo", "localhost:6379")
conn, err := yiigo.Redis("foo").Get()
if err != nil {
log.Fatal(err)
}
defer yiigo.Redis("foo").Put(conn)
conn.Do("SET", "test_key", "hello world")
Config
// env.toml
//
// [app]
// env = "dev"
// debug = true
// port = 50001
yiigo.SetEnvFile("env.toml")
yiigo.Env.Bool("app.debug", true)
yiigo.Env.Int("app.port", 12345)
yiigo.Env.String("app.env", "dev")
Zipkin
reporter := yiigo.NewZipkinHTTPReporter("http://localhost:9411/api/v2/spans")
err := yiigo.RegisterZipkinTracer(yiigo.AsDefault, reporter)
if err != nil {
log.Fatal(err)
}
client, err := yiigo.ZTracer().HTTPClient()
if err != nil {
log.Fatal(err)
}
b, err := client.Get(context.Background(), "url...",
yiigo.WithRequestHeader("Content-Type", "application/json; charset=utf-8"),
yiigo.WithRequestTimeout(5*time.Second),
)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(b))
Logger
// default logger
yiigo.RegisterLogger(yiigo.AsDefault, "app.log")
yiigo.Logger().Info("hello world")
// other logger
yiigo.RegisterLogger("foo", "foo.log")
yiigo.Logger("foo").Info("hello world")
Documentation
Enjoy 😊
# Functions
AddSlashes returns a string with backslashes added before characters that need to be escaped.
AESCBCDecrypt AES CBC decrypt with PKCS#7 unpadding.
AESCBCEncrypt AES CBC encrypt with PKCS#7 padding.
Date format a local time/date and returns a string formatted according to the given format string using the given timestamp of int64.
DB returns a db.
Float64sUnique takes an input slice of float64s and returns a new slice of float64s without duplicate values.
Hash Generate a hash value, expects: MD5, SHA1, SHA224, SHA256, SHA384, SHA512.
HMAC Generate a keyed hash value, expects: MD5, SHA1, SHA224, SHA256, SHA384, SHA512.
HTTPGet http get request.
HTTPPost http post request.
InArray checks if x exists in a slice and returns TRUE if x is found.
InFloat64s checks if x exists in []float64s and returns TRUE if x is found.
InInt16s checks if x exists in []int16s and returns TRUE if x is found.
InInt32s checks if x exists in []int32s and returns TRUE if x is found.
InInt64s checks if x exists in []int64s and returns TRUE if x is found.
InInt8s checks if x exists in []int8s and returns TRUE if x is found.
InInts checks if x exists in []ints and returns TRUE if x is found.
InsertSQL returns mysql insert sql and binds.
InStrings checks if x exists in []strings and returns TRUE if x is found.
Int16sUnique takes an input slice of int16s and returns a new slice of int16s without duplicate values.
Int32sUnique takes an input slice of int32s and returns a new slice of int32s without duplicate values.
Int64sUnique takes an input slice of int64s and returns a new slice of int64s without duplicate values.
Int8sUnique takes an input slice of int8s and returns a new slice of int8s without duplicate values.
IntsUnique takes an input slice of ints and returns a new slice of ints without duplicate values.
InUint16s checks if x exists in []uint16s and returns TRUE if x is found.
InUint32s checks if x exists in []uint32s and returns TRUE if x is found.
InUint64s checks if x exists in []uint64s and returns TRUE if x is found.
InUint8s checks if x exists in []uint8s and returns TRUE if x is found.
InUints checks if x exists in []uints and returns TRUE if x is found.
IP2Long converts a string containing an (IPv4) Internet Protocol dotted address into a long integer.
Logger returns a logger.
Long2IP converts an long integer address into a string in (IPv4) Internet standard dotted format.
Mailer returns a mailer.
MD5 calculate the md5 hash of a string.
Mongo returns a mongo client.
MyTimeEncoder zap time encoder.
NewHTTPClient returns a new http client.
NewZipkinHTTPReporter returns a new zipin http reporter.
Orm returns an orm.
PGInsertSQL returns postgres insert sql and binds.
PGUpdateSQL returns postgres update sql and binds.
PKCS7Padding PKCS#7 padding.
PKCS7UnPadding PKCS#7 unpadding.
QuoteMeta returns a version of str with a backslash character (\) before every character that is among these: .
Redis returns a redis pool.
RegisterDB register a db, the param `dsn` eg:
MySQL: `username:password@tcp(localhost:3306)/dbname?timeout=10s&charset=utf8mb4&collation=utf8mb4_general_ci&parseTime=True&loc=Local`;
Postgres: `host=localhost port=5432 user=root password=secret dbname=test connect_timeout=10 sslmode=disable`.
RegisterLogger register logger.
RegisterMailer register a mailer.
RegisterMongoDB register a mongodb, the param `dsn` eg: `mongodb://username:password@localhost:27017`.
RegisterRedis register a redis.
RegisterZipkinTracer register a zipkin tracer.
SearchInt16s searches for x in a sorted slice of int16s and returns the index as specified by Search.
SearchInt32s searches for x in a sorted slice of int32s and returns the index as specified by Search.
SearchInt64s searches for x in a sorted slice of int64s and returns the index as specified by Search.
SearchInt8s searches for x in a sorted slice of int8s and returns the index as specified by Search.
SearchUints searches for x in a sorted slice of uint16s and returns the index as specified by Search.
SearchUint32s searches for x in a sorted slice of uint32s and returns the index as specified by Search.
SearchUint64s searches for x in a sorted slice of uint64s and returns the index as specified by Search.
SearchUint8s searches for x in a sorted slice of uint8s and returns the index as specified by Search.
SearchUints searches for x in a sorted slice of uints and returns the index as specified by Search.
SetEnvFile use `toml` config file.
SHA1 calculate the sha1 hash of a string.
SortInt16s sorts []int16s in increasing order.
SortInt32s sorts []int32s in increasing order.
SortInt64s sorts []int64s in increasing order.
SortInt8s sorts []int8s in increasing order.
SortUint16s sorts []uint16s in increasing order.
SortUint32s sorts []uint32s in increasing order.
SortUint64s sorts []uint64s in increasing order.
SortUint8s sorts []uint8s in increasing order.
SortUints sorts []uints in increasing order.
StringsUnique takes an input slice of strings and returns a new slice of strings without duplicate values.
StripSlashes returns a string with backslashes stripped off.
Uint16sUnique takes an input slice of uint16s and returns a new slice of uint16s without duplicate values.
Uint32sUnique takes an input slice of uint32s and returns a new slice of uint32s without duplicate values.
Uint64sUnique takes an input slice of uint64s and returns a new slice of uint64s without duplicate values.
Uint8sUnique takes an input slice of uint8s and returns a new slice of uint8s without duplicate values.
UintsUnique takes an input slice of uints and returns a new slice of uints without duplicate values.
UpdateSQL returns mysql update sql and binds.
WithDBConnMaxLifetime specifies the `ConnMaxLifetime` to db.
WithDBDebug specifies the `LogMod` to orm.
WithDBMaxIdleConns specifies the `MaxIdleConns` to db.
WithDBMaxOpenConns specifies the `MaxOpenConns` to db.
WithEMailCharset specifies the `Charset` to email.
WithEMailContentType specifies the `ContentType` to email.
WithEMailEncoding specifies the `Encoding` to email.
WithHTTPDefaultTimeout specifies the `DefaultTimeout` to http client.
WithHTTPDialFallbackDelay specifies the `FallbackDelay` to net.Dialer.
WithHTTPDialKeepAlive specifies the `KeepAlive` to net.Dialer.
WithHTTPDialTimeout specifies the `DialTimeout` to net.Dialer.
WithHTTPExpectContinueTimeout specifies the `ExpectContinueTimeout` to http client.
WithHTTPIdleConnTimeout specifies the `IdleConnTimeout` to http client.
WithHTTPMaxConnsPerHost specifies the `MaxConnsPerHost` to http client.
WithHTTPMaxIdleConns specifies the `MaxIdleConns` to http client.
WithHTTPMaxIdleConnsPerHost specifies the `MaxIdleConnsPerHost` to http client.
WithHTTPTLSConfig specifies the `TLSClientConfig` to http client.
WithHTTPTLSHandshakeTimeout specifies the `TLSHandshakeTimeout` to http client.
WithLogCompress specifies the `Compress` to logger.
WithLogDebug specifies the `Debug` mode to logger.
WithLogMaxAge specifies the `MaxAge` to logger.
WithLogMaxBackups specifies the `MaxBackups` to logger.
WithLogMaxSize specifies the `MaxSize` to logger.
WithMongoAppName specifies the `AppName` to mongo.
WithMongoCompressors specifies the `Compressors` to mongo.
WithMongoConnTimeout specifies the `ConnTimeout` to mongo.
WithMongoDirect specifies the `Direct` to mongo.
WithMongoHeartbeatInterval specifies the `HeartbeatInterval` to mongo.
WithMongoHosts specifies the `Hosts` to mongo.
WithMongoLocalThreshold specifies the `LocalThreshold` to mongo.
WithMongoMaxConnIdleTime specifies the `MaxConnIdleTime` to mongo.
WithMongoMode specifies the `Mode` to mongo.
WithMongoPoolSize specifies the `PoolSize` to mongo.
WithMongoReadConcern specifies the `ReadConcern` to mongo.
WithMongoReplicaSet specifies the `ReplicaSet` to mongo.
WithMongoRetryWrites specifies the `RetryWrites` to mongo.
WithMongoServerSelectionTimeout specifies the `ServerSelectionTimeout` to mongo.
WithMongoSocketTimeout specifies the `SocketTimeout` to mongo.
WithMongoTLSConfig specifies the `TLSConfig` to mongo.
WithMongoWriteConcern specifies the `WriteConcern` to mongo.
WithMongoZlibLevel specifies the `ZlibLevel` to mongo.
WithRedisConnTimeout specifies the `ConnTimeout` to redis.
WithRedisDatabase specifies the `Database` to redis.
WithRedisIdleTimeout specifies the `IdleTimeout` to redis.
WithRedisPassword specifies the `Password` to redis.
WithRedisPoolLimit specifies the `PoolLimit` to redis.
WithRedisPoolSize specifies the `PoolSize` to redis.
WithRedisPrefillParallelism specifies the `PrefillParallelism` to redis.
WithRedisReadTimeout specifies the `ReadTimeout` to redis.
WithRedisWaitTimeout specifies the `WaitTimeout` to redis.
WithRedisWriteTimeout specifies the `WriteTimeout` to redis.
WithRequestClose specifies close the connection after replying to this request (for servers) or after sending this request and reading its response (for clients).
WithRequestCookies specifies the cookies to http request.
WithRequestHeader specifies the header to http request.
WithRequestTimeout specifies the timeout to http request.
WithZipkinClientOptions specifies the `Options` to zipkin http client.
WithZipkinHTTPClient specifies the `Client` to zipkin http client.
WithZipkinHTTPTransport specifies the `Transport` to zipkin http client transport.
WithZipkinReporterClient specifies the `Client` to zipkin reporter.
WithZipkinReporterOptions specifies the `Options` to zipkin reporter.
WithZipkinSpanTag specifies the zipkin span tag to zipkin http request.
ZTracer returns a zipkin tracer.
# Constants
AsDefault alias for "default".
the query should return data from the instance with no guarantee that the data has been written to a majority of the replica set members (i.e.
that the query should return data that reflects all successful writes issued with a write concern of "majority" and acknowledged prior to the start of the read operation.
the query should return the instance’s most recent data.
the query should return the instance’s most recent data acknowledged as having been written to a majority of members in the replica set.
No description provided by the author
Read from one of the nearest members, irrespective of it being primary or secondary.
No description provided by the author
Default mode.
Read from the primary if available.
Read from one of the nearest secondary members of the replica set.
Read from one of the nearest secondaries if available.
only available for operations within multi-document transactions.
# Structs
EMail email.
EMailDialer email dialer.
HTTPClient http client.
RedisConn redis connection resource.
RedisPoolResource redis pool resource.
ZipkinHTTPClient zipkin http client.
ZipkinTracer zipkin tracer.
# Interfaces
DBOption configures how we set up the db.
EMailOption configures how we set up the email.
HTTPClientOption configures how we set up the http client.
HTTPRequestOption configures how we set up the http request.
LogOption configures how we set up the logger.
MongoOption configures how we set up the mongo.
RedisOption configures how we set up the db.
ZipkinHTTPClientOption configures how we set up the zipkin http client.
ZipkinReporterOption configures how we set up the zipkin reporter.
# Type aliases
CDATA XML CDATA section which is defined as blocks of text that are not parsed by the parser, but are otherwise recognized as markup.
Concern for replica sets and replica set shards determines which data to return from a query.
DBDriver indicates the db drivers.
Int16Slice attaches the methods of Interface to []int16, sorting a increasing order.
Int32Slice attaches the methods of Interface to []int32, sorting a increasing order.
Int64Slice attaches the methods of Interface to []int64, sorting a increasing order.
Int8Slice attaches the methods of Interface to []int8, sorting a increasing order.
Mode indicates the user's preference on reads.
Uint16Slice attaches the methods of Interface to []uint16, sorting a increasing order.
Uint32Slice attaches the methods of Interface to []uint, sorting a increasing order.
Uint64Slice attaches the methods of Interface to []uint64, sorting a increasing order.
Uint8Slice attaches the methods of Interface to []uint8, sorting a increasing order.
UintSlice attaches the methods of Interface to []uint, sorting a increasing order.
X is a convenient alias for a map[string]interface{}.