Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinBlandy committed May 31, 2023
1 parent 754c48a commit b0e43b3
Show file tree
Hide file tree
Showing 16 changed files with 602 additions and 11 deletions.
2 changes: 1 addition & 1 deletion Codings/ZipUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ public static void unZip(Path file, Path targetDir) throws IOException {
Files.createDirectories(targetDir);
}
// 创建zip对象
try (ZipFile zipFile = new ZipFile(file.toFile())) {
try (ZipFile zipFile = new ZipFile(file.toFile(), StandardCharsets.UTF_8))) {
// 读取zip流
try (ZipInputStream zipInputStream = new ZipInputStream(Files.newInputStream(file))) {
ZipEntry zipEntry = null;
Expand Down
9 changes: 9 additions & 0 deletions Go/go-数据类型-字符串.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@

# 获取字符串的字节长度使用全局函数 len
var size int = len("Hello")

* 注意这个长度是字节长度不是字符长度

# 获取字符长度使用"unicode/utf8"包中的方法
import (
Expand Down Expand Up @@ -109,6 +111,13 @@
str := "Hello World"
sub := str[1:]
fmt.Printf("%T=%s\n", sub, sub) // string=ello World

* 注意这个是按照字节切片如果包含非ascii字符的话会导致乱码
v := "你好啊,世界"
fmt.Println(v[1:]) // <乱码><乱码>好啊,世界

* 如果需要按照字符切片先转换为字符数组


# 字符串的比较可以使用 >,<,==
* 比较的本质上是挨着比较每一个字节直到比较出结果
Expand Down
6 changes: 6 additions & 0 deletions Go/lib/encoding/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,13 @@ struct
<nil>

func (dec *Decoder) UseNumber()
* 将一个数字作为Number而不是float64解码到 interface{}。
* 使用Number代替json中的float64
kv := map[string]any{}
d := json.NewDecoder(...)
d.UseNumber()
d.Decode(&kv)


# type Delim rune
func (d Delim) String() string
Expand Down
102 changes: 102 additions & 0 deletions Go/三方框架/captcha.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
------------------
captcha
------------------
# 简单不依赖第三方框架的一个验证码图片类
https://github.com/steambap/captcha

* 支持Gif/Png/Jpeg/算术计算


------------------
Demo
------------------
package service

import (
"context"
"github.com/gin-gonic/gin"
"github.com/redis/go-redis/v9"
cpt "github.com/steambap/captcha"
"go.uber.org/zap"
"springdoc/common/constant/header"
"springdoc/common/errors"
"springdoc/common/response"
"springdoc/common/util/id"
"springdoc/log"
"springdoc/rdb"
"strconv"
"strings"
"time"
)

func init() {
// 加载字体
//err := cpt.LoadFont(goregular.TTF)
//if err != nil {
// panic(err)
//}
}

type captcha struct {
namespace string
duration time.Duration
}

func (c captcha) key(id string) string {
return c.namespace + id
}

// Gen 生成图片验证码
func (c captcha) Gen(ctx *gin.Context) error {

// 生成验证码图片
image, err := cpt.New(150, 50, func(options *cpt.Options) {
options.TextLength = 6 // 字符长度
options.CurveNumber = 4 // 干扰线数量
//options.Noise = 4.0 // 噪点数量。默认情况下,每28个像素就画一个噪声点。默认是1.0。
})
if err != nil {
return err
}

// id & 文本
captchaId := strconv.FormatInt(id.Next(), 10)
text := image.Text

log.Info("captcha", zap.String("id", captchaId), zap.String("text", text))

// 刷到redis缓存
if err := rdb.Client().Set(context.Background(), c.key(captchaId), text, time.Second*30).Err(); err != nil {
return err
}

ctx.Header(header.XCaptchaId, captchaId)
ctx.Header(header.ContentType, "image/png")
ctx.Header(header.CacheControl, "no-cache, no-store")
ctx.Header(header.Pragma, "no-cache")

//return image.WriteGIF(ctx.Writer, &gif.Options{
// NumColors: 256, // NumColors是图像中使用的最大颜色数。它的范围是1到256。
// Quantizer: nil, //palette.Plan9被用来代替nil Quantizer,它被用来生成一个具有NumColors大小的调色板。
// Drawer: nil, // draw.FloydSteinberg用于将源图像转换为所需的调色板。Draw.FloydSteinberg用于替代一个无的Drawer。
//})
return image.WriteImage(ctx.Writer)
}

// Validate 校验验证码是否正确
func (c captcha) Validate(id string, text string) (bool, error) {
cmd := rdb.Client().GetDel(context.Background(), c.key(id))
if cmd.Err() == redis.Nil {
return false, errors.New(response.Fail(response.StatusCodeCaptchaRequired).SetMessage("需要验证码"))
}
if cmd.Err() != nil {
return false, cmd.Err()
}
if !strings.EqualFold(cmd.Val(), text) {
return false, errors.New(response.Fail(response.StatusCodeWrongCaptcha).SetMessage("验证码错误"))
}
return true, nil
}

var Captcha = &captcha{namespace: "CAPTCHA::", duration: time.Second * 30}

119 changes: 118 additions & 1 deletion Go/三方框架/decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,121 @@ decimal
https://github.com/shopspring/decimal



-------------
var
-------------
var DivisionPrecision = 16
var ExpMaxIterations = 1000
var MarshalJSONWithoutQuotes = false
* 是否使用数值的方式序列化 decimal 类型
* 建议为false如果为true的话可能会导致JS之类的丢失精度

var Zero = New(0, 1)

-------------
type
-------------

# type Decimal struct {
// contains filtered or unexported fields
}
func Avg(first Decimal, rest ...Decimal) Decimal
func Max(first Decimal, rest ...Decimal) Decimal
func Min(first Decimal, rest ...Decimal) Decimal
func New(value int64, exp int32) Decimal
func NewFromBigInt(value *big.Int, exp int32) Decimal
func NewFromFloat(value float64) Decimal
func NewFromFloat32(value float32) Decimal
func NewFromFloatWithExponent(value float64, exp int32) Decimal
func NewFromFormattedString(value string, replRegexp *regexp.Regexp) (Decimal, error)
func NewFromInt(value int64) Decimal
func NewFromInt32(value int32) Decimal
func NewFromString(value string) (Decimal, error)
func RequireFromString(value string) Decimal
func Sum(first Decimal, rest ...Decimal) Decimal

func (d Decimal) Abs() Decimal
func (d Decimal) Add(d2 Decimal) Decimal
func (d Decimal) Atan() Decimal
func (d Decimal) BigFloat() *big.Float
func (d Decimal) BigInt() *big.Int
func (d Decimal) Ceil() Decimal
func (d Decimal) Cmp(d2 Decimal) int
func (d Decimal) Coefficient() *big.Int
func (d Decimal) CoefficientInt64() int64
func (d Decimal) Copy() Decimal
func (d Decimal) Cos() Decimal
func (d Decimal) Div(d2 Decimal) Decimal
func (d Decimal) DivRound(d2 Decimal, precision int32) Decimal
func (d Decimal) Equal(d2 Decimal) bool
func (d Decimal) Equals(d2 Decimal) bool
func (d Decimal) ExpHullAbrham(overallPrecision uint32) (Decimal, error)
func (d Decimal) ExpTaylor(precision int32) (Decimal, error)
func (d Decimal) Exponent() int32
func (d Decimal) Float64() (f float64, exact bool)
func (d Decimal) Floor() Decimal
func (d *Decimal) GobDecode(data []byte) error
func (d Decimal) GobEncode() ([]byte, error)
func (d Decimal) GreaterThan(d2 Decimal) bool
func (d Decimal) GreaterThanOrEqual(d2 Decimal) bool
func (d Decimal) InexactFloat64() float64
func (d Decimal) IntPart() int64
func (d Decimal) IsInteger() bool
func (d Decimal) IsNegative() bool
func (d Decimal) IsPositive() bool
func (d Decimal) IsZero() bool
func (d Decimal) LessThan(d2 Decimal) bool
func (d Decimal) LessThanOrEqual(d2 Decimal) bool
func (d Decimal) MarshalBinary() (data []byte, err error)
func (d Decimal) MarshalJSON() ([]byte, error)
func (d Decimal) MarshalText() (text []byte, err error)
func (d Decimal) Mod(d2 Decimal) Decimal
func (d Decimal) Mul(d2 Decimal) Decimal
func (d Decimal) Neg() Decimal
func (d Decimal) NumDigits() int
func (d Decimal) Pow(d2 Decimal) Decimal
func (d Decimal) QuoRem(d2 Decimal, precision int32) (Decimal, Decimal)
func (d Decimal) Rat() *big.Rat
func (d Decimal) Round(places int32) Decimal
func (d Decimal) RoundBank(places int32) Decimal
func (d Decimal) RoundCash(interval uint8) Decimal
func (d Decimal) RoundCeil(places int32) Decimal
func (d Decimal) RoundDown(places int32) Decimal
func (d Decimal) RoundFloor(places int32) Decimal
func (d Decimal) RoundUp(places int32) Decimal
func (d *Decimal) Scan(value interface{}) error
func (d Decimal) Shift(shift int32) Decimal
func (d Decimal) Sign() int
func (d Decimal) Sin() Decimal
func (d Decimal) String() string
func (d Decimal) StringFixed(places int32) string
func (d Decimal) StringFixedBank(places int32) string
func (d Decimal) StringFixedCash(interval uint8) string
func (d Decimal) StringScaled(exp int32) string
func (d Decimal) Sub(d2 Decimal) Decimal
func (d Decimal) Tan() Decimal
func (d Decimal) Truncate(precision int32) Decimal
func (d *Decimal) UnmarshalBinary(data []byte) error
func (d *Decimal) UnmarshalJSON(decimalBytes []byte) error
func (d *Decimal) UnmarshalText(text []byte) error
func (d Decimal) Value() (driver.Value, error)

# type NullDecimal struct {
Decimal Decimal
Valid bool
}

* NullDecimal表示一个可空的 Decimal具有从数据库 scanl null 的兼容性

func NewNullDecimal(d Decimal) NullDecimal
func (d NullDecimal) MarshalJSON() ([]byte, error)
func (d NullDecimal) MarshalText() (text []byte, err error)
func (d *NullDecimal) Scan(value interface{}) error
func (d *NullDecimal) UnmarshalJSON(decimalBytes []byte) error
func (d *NullDecimal) UnmarshalText(text []byte) error
func (d NullDecimal) Value() (driver.Value, error)

-------------
func
-------------
func RescalePair(d1 Decimal, d2 Decimal) (Decimal, Decimal)
98 changes: 98 additions & 0 deletions Go/三方框架/eventbus.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
----------------
EventBus
----------------

package bus

import (
"context"
"errors"
"fmt"
"reflect"
)

/*
Bus
https://github.com/grafana/grafana/blob/main/pkg/bus/bus.go
根据 HandlerFunc 的第二个参数类型的名称来确定 Handler
HandlerFunc 函数第一个参数必须是 context, 第二个参数必须是事件对象指针,返回值必须是 error
*/

// HandlerFunc defines a handler function interface.
type HandlerFunc any

// Msg defines a message interface.
type Msg any

// ErrHandlerNotFound defines an error if a handler is not found.
var ErrHandlerNotFound = errors.New("handler not found")

// Bus type defines the bus interface structure.
type Bus interface {
Publish(ctx context.Context, msg Msg) error
AddEventListener(handler HandlerFunc)
}

// InProcBus defines the bus structure.
type InProcBus struct {
listeners map[string][]HandlerFunc
}

func ProvideBus() *InProcBus {
return &InProcBus{
listeners: make(map[string][]HandlerFunc),
}
}

// Publish function publish a message to the bus listener.
func (b *InProcBus) Publish(ctx context.Context, msg Msg) error {
var msgName = reflect.TypeOf(msg).Elem().Name()

var params []reflect.Value
if listeners, exists := b.listeners[msgName]; exists {
params = append(params, reflect.ValueOf(ctx))
params = append(params, reflect.ValueOf(msg))
if err := callListeners(listeners, params); err != nil {
return err
}
}

return ErrHandlerNotFound
}

func callListeners(listeners []HandlerFunc, params []reflect.Value) error {
for _, listenerHandler := range listeners {
ret := reflect.ValueOf(listenerHandler).Call(params)
e := ret[0].Interface()
if e != nil {
err, ok := e.(error)
if ok {
return err
}
return fmt.Errorf("expected listener to return an error, got '%T'", e)
}
}
return nil
}

func (b *InProcBus) AddEventListener(handler HandlerFunc) {
handlerType := reflect.TypeOf(handler)
eventName := handlerType.In(1).Elem().Name()
_, exists := b.listeners[eventName]
if !exists {
b.listeners[eventName] = make([]HandlerFunc, 0)
}
b.listeners[eventName] = append(b.listeners[eventName], handler)
}

var bus = ProvideBus()

func Initialization(listener ...HandlerFunc) {
for _, v := range listener {
bus.AddEventListener(v)
}
}
func Publish(ctx context.Context, msg Msg) error {
return bus.Publish(ctx, msg)
}
3 changes: 2 additions & 1 deletion Go/三方框架/gin/gin-静态资源路由.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,9 @@ func FsHandler(fs http.FileSystem) gin.HandlerFunc {
return
}

closeFile := reqFile // reqFile 如果是文件夹,并且文件夹内有index.xml,则该变量会被重置
defer func() {
_ = reqFile.Close()
_ = closeFile.Close()
}()

reqFileStat, err := reqFile.Stat()
Expand Down
Loading

0 comments on commit b0e43b3

Please sign in to comment.