Skip to content

Commit

Permalink
Add new files and functions
Browse files Browse the repository at this point in the history
  • Loading branch information
shenghui0779 committed Jan 25, 2024
1 parent 87dbf26 commit 56df1ca
Show file tree
Hide file tree
Showing 24 changed files with 1,397 additions and 133 deletions.
4 changes: 0 additions & 4 deletions coord/location.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,21 +77,17 @@ func (l *Location) Azimuth(t *Location) float64 {
sinc := math.Sqrt(1 - cosc*cosc)

sinA := math.Sin(a) * math.Sin(AOC_BOC) / sinc

if sinA > 1 {
sinA = 1
}

if sinA < -1 {
sinA = -1
}

angle := math.Asin(sinA) / math.Pi * 180

if t.lat < l.lat {
return 180 - angle
}

if t.lng < l.lng {
return 360 + angle
}
Expand Down
59 changes: 41 additions & 18 deletions db/db.go → db.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package db
package yiigo

import (
"context"
"database/sql"
"fmt"
"time"

_ "github.com/go-sql-driver/mysql"
Expand All @@ -10,21 +12,15 @@ import (
_ "github.com/mattn/go-sqlite3"
)

// Config 数据库初始化配置
type Config struct {
// DBConfig 数据库初始化配置
type DBConfig struct {
// Driver 驱动名称
Driver string
// DSN 数据源名称
// [-- 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
// [- SQLite] file::memory:?cache=shared
DSN string
// Options 配置选项
Options *Options
}

// Options 数据库配置选项
type Options struct {
// MaxOpenConns 设置最大可打开的连接数
MaxOpenConns int
// MaxIdleConns 连接池最大闲置连接数
Expand All @@ -35,7 +31,7 @@ type Options struct {
ConnMaxIdleTime time.Duration
}

func New(cfg *Config) (*sql.DB, error) {
func NewDB(cfg *DBConfig) (*sql.DB, error) {
db, err := sql.Open(cfg.Driver, cfg.DSN)
if err != nil {
return nil, err
Expand All @@ -45,21 +41,48 @@ func New(cfg *Config) (*sql.DB, error) {
return nil, err
}

if cfg.Options != nil {
db.SetMaxOpenConns(cfg.Options.MaxOpenConns)
db.SetMaxIdleConns(cfg.Options.MaxIdleConns)
db.SetConnMaxLifetime(cfg.Options.ConnMaxLifetime)
db.SetConnMaxIdleTime(cfg.Options.ConnMaxIdleTime)
}
db.SetMaxOpenConns(cfg.MaxOpenConns)
db.SetMaxIdleConns(cfg.MaxIdleConns)
db.SetConnMaxLifetime(cfg.ConnMaxLifetime)
db.SetConnMaxIdleTime(cfg.ConnMaxIdleTime)

return db, nil
}

func NewX(cfg *Config) (*sqlx.DB, error) {
db, err := New(cfg)
func NewDBX(cfg *DBConfig) (*sqlx.DB, error) {
db, err := NewDB(cfg)
if err != nil {
return nil, err
}

return sqlx.NewDb(db, cfg.Driver), nil
}

// Transaction 执行数据库事物
func Transaction(ctx context.Context, db *sqlx.DB, f func(ctx context.Context, tx *sqlx.Tx) error) error {
tx, err := db.BeginTxx(ctx, nil)
if err != nil {
return err
}

defer func() {
if v := recover(); v != nil {
tx.Rollback()
panic(v)
}
}()

if err = f(ctx, tx); err != nil {
if rerr := tx.Rollback(); rerr != nil {
err = fmt.Errorf("%w: rolling back transaction: %v", err, rerr)
}

return err
}

if err = tx.Commit(); err != nil {
return fmt.Errorf("committing transaction: %w", err)
}

return nil
}
37 changes: 0 additions & 37 deletions db/transaction.go

This file was deleted.

2 changes: 1 addition & 1 deletion util/file.go → file.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package util
package yiigo

import (
"os"
Expand Down
2 changes: 1 addition & 1 deletion util/file_test.go → file_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package util
package yiigo

import (
"fmt"
Expand Down
2 changes: 1 addition & 1 deletion util/form.go → form.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package util
package yiigo

import (
"encoding/json"
Expand Down
2 changes: 1 addition & 1 deletion util/form_test.go → form_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package util
package yiigo

import (
"reflect"
Expand Down
5 changes: 1 addition & 4 deletions util/helper.go → helper.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package util
package yiigo

import (
"bytes"
Expand All @@ -11,9 +11,6 @@ import (
"github.com/hashicorp/go-version"
)

// X 类型别名
type X map[string]any

// Nonce 生成随机串(size应为偶数)
func Nonce(size uint8) string {
nonce := make([]byte, size/2)
Expand Down
2 changes: 1 addition & 1 deletion util/helper_test.go → helper_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package util
package yiigo

import (
"testing"
Expand Down
2 changes: 1 addition & 1 deletion util/ip.go → ip.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package util
package yiigo

import "net"

Expand Down
2 changes: 1 addition & 1 deletion util/ip_test.go → ip_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package util
package yiigo

import (
"testing"
Expand Down
53 changes: 20 additions & 33 deletions logger/zap.go → logger.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package logger
package yiigo

import (
"os"
Expand All @@ -9,16 +9,10 @@ import (
"gopkg.in/natefinch/lumberjack.v2"
)

// Config 日志初始化配置
type Config struct {
// LogConfig 日志初始化配置
type LogConfig struct {
// Filename 日志名称
Filename string
// Options 日志选项
Options *Options
}

// Options 日志配置选项
type Options struct {
// MaxSize 当前文件多大时轮替;默认:100MB
MaxSize int
// MaxAge 轮替的旧文件最大保留时长;默认:不限
Expand All @@ -29,11 +23,11 @@ type Options struct {
Compress bool
// Stderr 是否输出到控制台
Stderr bool
// ZapOpts Zap日志选项
ZapOpts []zap.Option
// Options Zap日志选项
Options []zap.Option
}

func Debug(options ...zap.Option) *zap.Logger {
func DebugLogger(options ...zap.Option) *zap.Logger {
cfg := zap.NewDevelopmentConfig()

cfg.DisableCaller = true
Expand All @@ -46,38 +40,31 @@ func Debug(options ...zap.Option) *zap.Logger {
return logger
}

func New(cfg *Config) *zap.Logger {
func NewLogger(cfg *LogConfig) *zap.Logger {
if len(cfg.Filename) == 0 {
return Debug()
return DebugLogger(cfg.Options...)
}

ec := zap.NewProductionEncoderConfig()
ec.TimeKey = "time"
ec.EncodeTime = MyTimeEncoder
ec.EncodeCaller = zapcore.FullCallerEncoder

var zapOpts []zap.Option

w := &lumberjack.Logger{
Filename: cfg.Filename,
LocalTime: true,
ws := []zapcore.WriteSyncer{
zapcore.AddSync(&lumberjack.Logger{
Filename: cfg.Filename,
MaxSize: cfg.MaxSize,
MaxAge: cfg.MaxAge,
MaxBackups: cfg.MaxBackups,
LocalTime: true,
Compress: cfg.Compress,
}),
}
ws := make([]zapcore.WriteSyncer, 0, 2)
if cfg.Options != nil {
zapOpts = cfg.Options.ZapOpts

w.MaxSize = cfg.Options.MaxSize
w.MaxAge = cfg.Options.MaxAge
w.MaxBackups = cfg.Options.MaxBackups
w.Compress = cfg.Options.Compress

if cfg.Options.Stderr {
ws = append(ws, zapcore.Lock(os.Stderr))
}
if cfg.Stderr {
ws = append(ws, zapcore.Lock(os.Stderr))
}
ws = append(ws, zapcore.AddSync(w))

return zap.New(zapcore.NewCore(zapcore.NewJSONEncoder(ec), zapcore.NewMultiWriteSyncer(ws...), zap.InfoLevel), zapOpts...)
return zap.New(zapcore.NewCore(zapcore.NewJSONEncoder(ec), zapcore.NewMultiWriteSyncer(ws...), zap.InfoLevel), cfg.Options...)
}

// MyTimeEncoder 自定义时间格式化
Expand Down
9 changes: 5 additions & 4 deletions mutex/distributed.go → mutex.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package redis
package yiigo

import (
"context"
Expand All @@ -7,14 +7,15 @@ import (
"github.com/redis/go-redis/v9"
)

// Mutex 基于Redis实现的分布式锁
// Mutex 分布式锁
type Mutex interface {
// Lock 尝试获取锁;interval - 每隔指定时间尝试获取一次锁;timeout - 获取锁的超时时间
Lock(ctx context.Context, interval, timeout time.Duration) error
// UnLock 释放锁
UnLock(ctx context.Context) error
}

// distributed 基于「Redis」实现的分布式锁
type distributed struct {
cli *redis.Client
key string
Expand Down Expand Up @@ -58,8 +59,8 @@ func (d *distributed) UnLock(ctx context.Context) error {
return d.cli.Del(ctx, d.key).Err()
}

// DistributedMutex 返回一个分布式锁实例
// uniqueID - 建议使用RequestID
// DistributedMutex 返回一个分布式锁实例
// uniqueID - 建议使用「RequestID」
func DistributedMutex(cli *redis.Client, key, uniqueID string, expire time.Duration) Mutex {
mutex := &distributed{
cli: cli,
Expand Down
13 changes: 8 additions & 5 deletions util/slice.go → slice.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
package util
package yiigo

import "math/rand"
import (
"cmp"
"math/rand"
)

// SliceUniq 切片去重
func SliceUniq[T ~int | ~int64 | ~float64 | ~string](a []T) []T {
ret := make([]T, 0)
func SliceUniq[T ~[]E, E cmp.Ordered](a T) T {
ret := make(T, 0)
if len(a) == 0 {
return ret
}

m := make(map[T]struct{}, 0)
m := make(map[E]struct{}, 0)

for _, v := range a {
if _, ok := m[v]; !ok {
Expand Down
2 changes: 1 addition & 1 deletion util/slice_test.go → slice_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package util
package yiigo

import (
"testing"
Expand Down
Loading

0 comments on commit 56df1ca

Please sign in to comment.