Compare commits

...

8 Commits

Author SHA1 Message Date
ayflying
92a127e128 包名改回来 2025-03-06 14:38:03 +08:00
ayflying
f654e0feda 更新 2025-03-06 11:53:18 +08:00
ayflying
d44810e174 更新包名 2025-03-06 11:50:17 +08:00
ayflying
843cdc94d4 修改ci 2025-03-06 11:36:17 +08:00
ayflying
dd1d6ce2a6 增加ci文件 2025-03-06 11:16:41 +08:00
ayflying
1df0172acc 忽略目录 2025-03-05 17:27:54 +08:00
ayflying
1a3d79a605 去掉多余文件 2025-03-05 17:22:03 +08:00
ayflying
0e55698a47 使用统一方法pgk进行调用 2025-03-04 18:58:10 +08:00
32 changed files with 1502 additions and 155 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
.idea/

36
.gitlab-ci.yml Normal file
View File

@@ -0,0 +1,36 @@
# This file is a template, and might need editing before it works on your project.
# You can copy and paste this template into a new `.gitlab-ci.yml` file.
# You should not add this template to an existing `.gitlab-ci.yml` file by using the `include:` keyword.
#
# To contribute improvements to CI/CD templates, please follow the Development guide at:
# https://docs.gitlab.com/ee/development/cicd/templates.html
# This specific template is located at:
# https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Go.gitlab-ci.yml
image: golang:latest
stages:
- test
# - build
# - deploy
format:
stage: test
script:
- go fmt $(go list ./... | grep -v /vendor/)
- go vet $(go list ./... | grep -v /vendor/)
- go test -race $(go list ./... | grep -v /vendor/)
#compile:
# stage: build
# script:
# - mkdir -p mybinaries
# - go build -o mybinaries main.go
# artifacts:
# paths:
# - build
#
#deploy:
# stage: deploy
# script: echo "Define your deployment script!"
# environment: production

8
.idea/.gitignore generated vendored
View File

@@ -1,8 +0,0 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="com.github.oldmegit.goframehelper.ui.goframehelperCache">
<option name="gf" value="true" />
</component>
</project>

8
.idea/modules.xml generated
View File

@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/utility-go.iml" filepath="$PROJECT_DIR$/.idea/utility-go.iml" />
</modules>
</component>
</project>

9
.idea/utility-go.iml generated
View File

@@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="Go" enabled="true" />
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

6
.idea/vcs.xml generated
View File

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

237
api/pgk/v1/pgk.pb.go Normal file
View File

@@ -0,0 +1,237 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.28.1
// protoc v3.20.0
// source: pgk/v1/pgk.proto
package v1
import (
reflect "reflect"
sync "sync"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// 定义 NoticeType 枚举
type NoticeType int32
const (
NoticeType_DINGTALK NoticeType = 0
NoticeType_WECHAT NoticeType = 1
NoticeType_EMAIL NoticeType = 2
NoticeType_SMS NoticeType = 3
NoticeType_VOICE NoticeType = 4
)
// Enum value maps for NoticeType.
var (
NoticeType_name = map[int32]string{
0: "DINGTALK",
1: "WECHAT",
2: "EMAIL",
3: "SMS",
4: "VOICE",
}
NoticeType_value = map[string]int32{
"DINGTALK": 0,
"WECHAT": 1,
"EMAIL": 2,
"SMS": 3,
"VOICE": 4,
}
)
func (x NoticeType) Enum() *NoticeType {
p := new(NoticeType)
*p = x
return p
}
func (x NoticeType) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (NoticeType) Descriptor() protoreflect.EnumDescriptor {
return file_pgk_v1_pgk_proto_enumTypes[0].Descriptor()
}
func (NoticeType) Type() protoreflect.EnumType {
return &file_pgk_v1_pgk_proto_enumTypes[0]
}
func (x NoticeType) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use NoticeType.Descriptor instead.
func (NoticeType) EnumDescriptor() ([]byte, []int) {
return file_pgk_v1_pgk_proto_rawDescGZIP(), []int{0}
}
// 排行榜数据
type RankData struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
Score int64 `protobuf:"varint,2,opt,name=score,proto3" json:"score,omitempty"`
Rank int32 `protobuf:"varint,3,opt,name=rank,proto3" json:"rank,omitempty"`
UpdateTs int64 `protobuf:"varint,4,opt,name=update_ts,json=updateTs,proto3" json:"update_ts,omitempty"`
}
func (x *RankData) Reset() {
*x = RankData{}
if protoimpl.UnsafeEnabled {
mi := &file_pgk_v1_pgk_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RankData) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RankData) ProtoMessage() {}
func (x *RankData) ProtoReflect() protoreflect.Message {
mi := &file_pgk_v1_pgk_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RankData.ProtoReflect.Descriptor instead.
func (*RankData) Descriptor() ([]byte, []int) {
return file_pgk_v1_pgk_proto_rawDescGZIP(), []int{0}
}
func (x *RankData) GetId() int64 {
if x != nil {
return x.Id
}
return 0
}
func (x *RankData) GetScore() int64 {
if x != nil {
return x.Score
}
return 0
}
func (x *RankData) GetRank() int32 {
if x != nil {
return x.Rank
}
return 0
}
func (x *RankData) GetUpdateTs() int64 {
if x != nil {
return x.UpdateTs
}
return 0
}
var File_pgk_v1_pgk_proto protoreflect.FileDescriptor
var file_pgk_v1_pgk_proto_rawDesc = []byte{
0x0a, 0x10, 0x70, 0x67, 0x6b, 0x2f, 0x76, 0x31, 0x2f, 0x70, 0x67, 0x6b, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x12, 0x07, 0x70, 0x61, 0x63, 0x6b, 0x61, 0x67, 0x65, 0x22, 0x61, 0x0a, 0x08, 0x52,
0x61, 0x6e, 0x6b, 0x44, 0x61, 0x74, 0x61, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20,
0x01, 0x28, 0x03, 0x52, 0x02, 0x69, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x73, 0x63, 0x6f, 0x72, 0x65,
0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x73, 0x63, 0x6f, 0x72, 0x65, 0x12, 0x12, 0x0a,
0x04, 0x72, 0x61, 0x6e, 0x6b, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x04, 0x72, 0x61, 0x6e,
0x6b, 0x12, 0x1b, 0x0a, 0x09, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x73, 0x18, 0x04,
0x20, 0x01, 0x28, 0x03, 0x52, 0x08, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x54, 0x73, 0x2a, 0x45,
0x0a, 0x0a, 0x4e, 0x6f, 0x74, 0x69, 0x63, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0c, 0x0a, 0x08,
0x44, 0x49, 0x4e, 0x47, 0x54, 0x41, 0x4c, 0x4b, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x57, 0x45,
0x43, 0x48, 0x41, 0x54, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x45, 0x4d, 0x41, 0x49, 0x4c, 0x10,
0x02, 0x12, 0x07, 0x0a, 0x03, 0x53, 0x4d, 0x53, 0x10, 0x03, 0x12, 0x09, 0x0a, 0x05, 0x56, 0x4f,
0x49, 0x43, 0x45, 0x10, 0x04, 0x42, 0x2b, 0x5a, 0x29, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e,
0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x79, 0x66, 0x6c, 0x79, 0x69, 0x6e, 0x67, 0x2f, 0x75, 0x74, 0x69,
0x6c, 0x69, 0x74, 0x79, 0x5f, 0x67, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x70, 0x67, 0x6b, 0x2f,
0x76, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_pgk_v1_pgk_proto_rawDescOnce sync.Once
file_pgk_v1_pgk_proto_rawDescData = file_pgk_v1_pgk_proto_rawDesc
)
func file_pgk_v1_pgk_proto_rawDescGZIP() []byte {
file_pgk_v1_pgk_proto_rawDescOnce.Do(func() {
file_pgk_v1_pgk_proto_rawDescData = protoimpl.X.CompressGZIP(file_pgk_v1_pgk_proto_rawDescData)
})
return file_pgk_v1_pgk_proto_rawDescData
}
var file_pgk_v1_pgk_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
var file_pgk_v1_pgk_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_pgk_v1_pgk_proto_goTypes = []interface{}{
(NoticeType)(0), // 0: package.NoticeType
(*RankData)(nil), // 1: package.RankData
}
var file_pgk_v1_pgk_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_pgk_v1_pgk_proto_init() }
func file_pgk_v1_pgk_proto_init() {
if File_pgk_v1_pgk_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_pgk_v1_pgk_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RankData); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_pgk_v1_pgk_proto_rawDesc,
NumEnums: 1,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_pgk_v1_pgk_proto_goTypes,
DependencyIndexes: file_pgk_v1_pgk_proto_depIdxs,
EnumInfos: file_pgk_v1_pgk_proto_enumTypes,
MessageInfos: file_pgk_v1_pgk_proto_msgTypes,
}.Build()
File_pgk_v1_pgk_proto = out.File
file_pgk_v1_pgk_proto_rawDesc = nil
file_pgk_v1_pgk_proto_goTypes = nil
file_pgk_v1_pgk_proto_depIdxs = nil
}

11
go.sum
View File

@@ -89,6 +89,8 @@ github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
@@ -236,11 +238,13 @@ github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa02
github.com/klauspost/cpuid/v2 v2.2.9 h1:66ze0taIn2H33fBvCkXuv9BmCwDfafmiIVpKV9kKGuY= github.com/klauspost/cpuid/v2 v2.2.9 h1:66ze0taIn2H33fBvCkXuv9BmCwDfafmiIVpKV9kKGuY=
github.com/klauspost/cpuid/v2 v2.2.9/go.mod h1:rqkxqrZ1EhYM9G+hXH7YdowN5R5RGN6NK4QwQ3WMXF8= github.com/klauspost/cpuid/v2 v2.2.9/go.mod h1:rqkxqrZ1EhYM9G+hXH7YdowN5R5RGN6NK4QwQ3WMXF8=
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lionsoul2014/ip2region/binding/golang v0.0.0-20241220152942-06eb5c6e8230 h1:B0oaMTAQKDZd8cwYT0qsAI7+c3KbFeBNA8GhgoBMXWw= github.com/lionsoul2014/ip2region/binding/golang v0.0.0-20241220152942-06eb5c6e8230 h1:B0oaMTAQKDZd8cwYT0qsAI7+c3KbFeBNA8GhgoBMXWw=
github.com/lionsoul2014/ip2region/binding/golang v0.0.0-20241220152942-06eb5c6e8230/go.mod h1:C5LA5UO2ZXJrLaPLYtE1wUJMiyd/nwWaCO5cw/2pSHs= github.com/lionsoul2014/ip2region/binding/golang v0.0.0-20241220152942-06eb5c6e8230/go.mod h1:C5LA5UO2ZXJrLaPLYtE1wUJMiyd/nwWaCO5cw/2pSHs=
github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60=
@@ -296,6 +300,8 @@ github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
@@ -306,7 +312,6 @@ github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIK
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/spf13/afero v1.6.0 h1:xoax2sJ2DT8S8xA2paPFjDCScCNeWsg75VG0DLRreiY= github.com/spf13/afero v1.6.0 h1:xoax2sJ2DT8S8xA2paPFjDCScCNeWsg75VG0DLRreiY=
github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I=
github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y= github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=

View File

@@ -9,6 +9,7 @@ gfcli:
pb: pb:
path: "manifest/protobuf" path: "manifest/protobuf"
api: "api" api: "api"
ctrl: "controller"
docker: docker:
build: "-a amd64 -s linux -p temp -ew" build: "-a amd64 -s linux -p temp -ew"
tagPrefixes: tagPrefixes:

View File

@@ -3,10 +3,10 @@ package systemCron
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/ayflying/utility_go/package/message" v1 "github.com/ayflying/utility_go/api/pgk/v1"
"github.com/ayflying/utility_go/pgk/notice"
"github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/gclient" "github.com/gogf/gf/v2/net/gclient"
"github.com/gogf/gf/v2/os/gtime"
) )
type Status struct { type Status struct {
@@ -29,14 +29,14 @@ func (s *sSystemCron) Guardian(DingTalkWebHook string) {
defer get.Close() defer get.Close()
if err != nil { if err != nil {
message.New(message.DingTalk, DingTalkWebHook).Send(fmt.Sprintf("监控报警:服务端访问失败 (%v 服务器),err=%v", v.Name, err)) notice.New(v1.NoticeType_DINGTALK, DingTalkWebHook).Send(fmt.Sprintf("监控报警:服务端访问失败 (%v 服务器),err=%v", v.Name, err))
} else if get.StatusCode != 200 { } else if get.StatusCode != 200 {
message.New(message.DingTalk, DingTalkWebHook).Send(fmt.Sprintf("监控报警:服务端访问失败 (%v 服务器),code=%v,err=%v", v.Name, get.StatusCode, err)) notice.New(v1.NoticeType_DINGTALK, DingTalkWebHook).Send(fmt.Sprintf("监控报警:服务端访问失败 (%v 服务器),code=%v,err=%v", v.Name, get.StatusCode, err))
} else { } else {
var ststus Status var ststus Status
err = json.Unmarshal(get.ReadAll(), &ststus) err = json.Unmarshal(get.ReadAll(), &ststus)
if ststus.Code != 0 { if ststus.Code != 0 {
message.New(message.DingTalk, DingTalkWebHook).Send(fmt.Sprintf("监控报警:服务端访问失败 (%v 服务器),msg=%v", v.Name, ststus.Message)) notice.New(v1.NoticeType_DINGTALK, DingTalkWebHook).Send(fmt.Sprintf("监控报警:服务端访问失败 (%v 服务器),msg=%v", v.Name, ststus.Message))
} }
} }
} }
@@ -49,28 +49,6 @@ func (s *sSystemCron) Guardian(DingTalkWebHook string) {
// @param value: 要发送的消息内容。 // @param value: 要发送的消息内容。
// Deprecated: Use message.New(message.DingTalk, DingTalkWebHook).Send(value) // Deprecated: Use message.New(message.DingTalk, DingTalkWebHook).Send(value)
func (s *sSystemCron) DingTalk(DingTalkWebHook string, value string) (res *gclient.Response) { func (s *sSystemCron) DingTalk(DingTalkWebHook string, value string) (res *gclient.Response) {
message.New(message.DingTalk, DingTalkWebHook).Send(value) notice.New(v1.NoticeType_DINGTALK, DingTalkWebHook).Send(value)
return
// 从配置中获取发送者名称
name, _ := g.Cfg().Get(ctx, "name")
// 定义钉钉机器人发送消息的URL其中access_token为固定值
url := DingTalkWebHook
url += "&timestamp=" + gtime.Now().TimestampMilliStr()
// 使用goroutine异步发送消息
var post = g.Map{
"msgtype": "text",
"text": g.Map{
"content": "通知姬 " + name.String() + "\n" + value + "\n" + gtime.Now().String(),
},
}
// 构建发送的消息体,包含消息类型和内容
res, err := g.Client().Discovery(nil).ContentJson().Post(ctx, url, post)
if err != nil {
g.Log().Info(ctx, err)
}
return return
} }

View File

@@ -1,13 +1,15 @@
package utility_go package utility_go
import ( import (
"context"
v1 "github.com/ayflying/utility_go/api/system/v1"
_ "github.com/ayflying/utility_go/internal/logic" _ "github.com/ayflying/utility_go/internal/logic"
"context"
"time"
v1 "github.com/ayflying/utility_go/api/system/v1"
"github.com/ayflying/utility_go/service" "github.com/ayflying/utility_go/service"
"github.com/gogf/gf/v2/os/gctx" "github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/os/gtimer" "github.com/gogf/gf/v2/os/gtimer"
"time"
"github.com/ayflying/utility_go/config" "github.com/ayflying/utility_go/config"
) )

View File

@@ -0,0 +1,22 @@
syntax = "proto3";
package package;
option go_package = "github.com/ayflying/utility_go/api/pgk/v1";
// 定义 NoticeType 枚举
enum NoticeType {
DINGTALK = 0;
WECHAT = 1;
EMAIL = 2;
SMS = 3;
VOICE = 4;
}
//排行榜数据
message RankData {
int64 id = 1;
int64 score = 2;
int32 rank = 3;
int64 update_ts = 4;
}

View File

@@ -1,4 +1,3 @@
syntax = "proto3"; syntax = "proto3";
package system; package system;

View File

@@ -13,6 +13,7 @@ type Mod struct {
// return pgk.Cache // return pgk.Cache
//} //}
// Deprecated: Use pgk.Cache()
func New(_name ...string) gcache.Adapter { func New(_name ...string) gcache.Adapter {
var cacheAdapterObj gcache.Adapter var cacheAdapterObj gcache.Adapter

View File

@@ -1,11 +0,0 @@
package message
type MessageType int32
const (
DingTalk MessageType = iota
Wechat
Email
Sms
Voice
)

View File

@@ -1,16 +0,0 @@
package message
import "github.com/ayflying/utility_go/package/message/drive"
type MessageV1 interface {
Send(value string)
}
func New(typ MessageType, host string) MessageV1 {
switch typ {
case DingTalk:
return drive.Load(host)
}
return nil
}

View File

@@ -1,51 +0,0 @@
package utility
import (
"github.com/ayflying/utility_go/tools"
"math/rand"
"time"
)
// rands 结构体用于封装 rand.Rand 实例,以提供随机数生成功能。
// 该结构体目前不包含锁,因此在多线程环境下使用时应注意同步问题。
type rands struct {
r *rand.Rand
// lock sync.Mutex
}
// Rand 是一个全局的 rands 实例,用于在整个程序中生成随机数。
// 它使用当前时间的毫秒值作为随机源,以确保每次程序运行时都能获得不同的随机数序列。
var Rand = rands{
r: rand.New(rand.NewSource(time.Now().UnixMilli())),
}
// RandByArrInt 函数从一个整数数组中按权重选择一个索引,并返回该索引。
// 权重是数组中相应元素的值。该函数通过计算累积和来确定选择的索引。
// 参数 v 是一个泛型参数,限制为实现了 Number 接口的类型。
// 返回值是一个整数,表示在数组中的索引。
func RandByArrInt[v tools.Number](s []v) int {
sv := 0
for i := range s {
sv += int(s[i])
}
r := Rand.Intn(sv)
var all v
for i := range s {
all += s[i]
if all > v(r) {
return i
}
}
return 0
}
// Intn 方法通过给定的整数 i 生成一个 0 到 i-1 之间的随机数。
// 如果 i 为0则会触发 panic。
// 参数 i 是一个整数,表示生成随机数的上限(不包含)。
// 返回值 ret 是一个在 0 到 i-1 范围内的随机整数。
func (r rands) Intn(i int) (ret int) {
if i == 0 {
panic(1)
}
return rand.Intn(i)
}

View File

@@ -21,13 +21,14 @@ type F64CountRank struct {
updateTs string // 更新时间key updateTs string // 更新时间key
} }
type Data struct { type RankData struct {
Id int64 Id int64
Score int64 Score int64
Rank int32 Rank int32
UpdateTs int64 UpdateTs int64
} }
// Deprecated:Use pgk.Rank()
func New() *Mod { func New() *Mod {
return &Mod{} return &Mod{}
} }
@@ -44,6 +45,8 @@ func (s *Mod) Load() {
// 返回值: // 返回值:
// //
// *F64CountRank: 返回一个指向新创建的F64CountRank实例的指针 // *F64CountRank: 返回一个指向新创建的F64CountRank实例的指针
//
// Deprecated:Use pgk.Rank().CreateF64CountRank(fmt.Sprintf("rank:%v", 1))
func (s *Mod) CreateF64CountRank(name string) *F64CountRank { func (s *Mod) CreateF64CountRank(name string) *F64CountRank {
// 初始化F64CountRank实例的name和updateTs字段 // 初始化F64CountRank实例的name和updateTs字段
// name字段用于标识排行榜的名称格式为"rank:<name>:score" // name字段用于标识排行榜的名称格式为"rank:<name>:score"
@@ -318,7 +321,7 @@ func (r *F64CountRank) UpdateScore(id int64, score int64) (err error) {
// //
// list - 排名信息列表 // list - 排名信息列表
// err - 错误信息,如果执行过程中遇到错误 // err - 错误信息,如果执行过程中遇到错误
func (r *F64CountRank) GetRankInfosNotTs(offset, count int) (list []*Data, err error) { func (r *F64CountRank) GetRankInfosNotTs(offset, count int) (list []*RankData, err error) {
// 初始化存储成员ID的切片 // 初始化存储成员ID的切片
var members []int64 var members []int64
@@ -338,7 +341,7 @@ func (r *F64CountRank) GetRankInfosNotTs(offset, count int) (list []*Data, err e
} }
// 根据获取的成员ID数量初始化排名信息列表 // 根据获取的成员ID数量初始化排名信息列表
list = make([]*Data, len(members)) list = make([]*RankData, len(members))
for i := range members { for i := range members {
// 获取当前成员ID // 获取当前成员ID
id := members[i] id := members[i]
@@ -358,9 +361,9 @@ func (r *F64CountRank) GetRankInfosNotTs(offset, count int) (list []*Data, err e
// 返回值: // 返回值:
// //
// rankInfo - 包含id的分数和排名信息的指针如果没有找到则返回nil // rankInfo - 包含id的分数和排名信息的指针如果没有找到则返回nil
func (r *F64CountRank) GetIdRankNotTs(id int64) (rankInfo *Data) { func (r *F64CountRank) GetIdRankNotTs(id int64) (rankInfo *RankData) {
// 初始化rankInfo结构体设置id其他字段将通过查询填充 // 初始化rankInfo结构体设置id其他字段将通过查询填充
rankInfo = &Data{Id: id} rankInfo = &RankData{Id: id}
// 查询有序集合中指定id的分数 // 查询有序集合中指定id的分数
score, err := g.Redis().ZScore(ctx, r.name, id) score, err := g.Redis().ZScore(ctx, r.name, id)

View File

@@ -36,6 +36,7 @@ type Mod struct {
cfg DataType cfg DataType
} }
// Deprecated: Use Pgk.S3()
func New(_name ...string) *Mod { func New(_name ...string) *Mod {
var name string var name string
if len(_name) > 0 { if len(_name) > 0 {

38
pgk/aycache/cache.go Normal file
View File

@@ -0,0 +1,38 @@
package aycache
import (
"github.com/ayflying/utility_go/package/aycache/drive"
drive2 "github.com/ayflying/utility_go/pgk/aycache/drive"
"github.com/gogf/gf/v2/os/gcache"
)
type Mod struct {
client *gcache.Cache
}
//func NewV1(_name ...string) *cache.Mod {
// return pgk.Cache
//}
func New(_name ...string) gcache.Adapter {
var cacheAdapterObj gcache.Adapter
var name = "cache"
if len(_name) > 0 {
name = _name[0]
}
switch name {
case "cache":
cacheAdapterObj = drive2.NewAdapterMemory()
case "redis":
cacheAdapterObj = drive2.NewAdapterRedis()
case "file":
cacheAdapterObj = drive2.NewAdapterFile("runtime/cache")
case "es":
cacheAdapterObj = drive.NewAdapterElasticsearch([]string{"http://127.0.0.1:9200"})
}
//var client = gcache.New()
//client.SetAdapter(cacheAdapterObj)
return cacheAdapterObj
}

View File

@@ -0,0 +1,119 @@
package drive
import (
"context"
"github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/os/gcache"
"time"
)
type AdapterElasticsearch struct {
//FilePath string
Addresses []string
}
func (a AdapterElasticsearch) Set(ctx context.Context, key interface{}, value interface{}, duration time.Duration) error {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) SetMap(ctx context.Context, data map[interface{}]interface{}, duration time.Duration) error {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) SetIfNotExist(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (ok bool, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) SetIfNotExistFunc(ctx context.Context, key interface{}, f gcache.Func, duration time.Duration) (ok bool, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) SetIfNotExistFuncLock(ctx context.Context, key interface{}, f gcache.Func, duration time.Duration) (ok bool, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) Get(ctx context.Context, key interface{}) (*gvar.Var, error) {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) GetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (result *gvar.Var, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) GetOrSetFunc(ctx context.Context, key interface{}, f gcache.Func, duration time.Duration) (result *gvar.Var, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) GetOrSetFuncLock(ctx context.Context, key interface{}, f gcache.Func, duration time.Duration) (result *gvar.Var, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) Contains(ctx context.Context, key interface{}) (bool, error) {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) Size(ctx context.Context) (size int, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) Data(ctx context.Context) (data map[interface{}]interface{}, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) Keys(ctx context.Context) (keys []interface{}, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) Values(ctx context.Context) (values []interface{}, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) Update(ctx context.Context, key interface{}, value interface{}) (oldValue *gvar.Var, exist bool, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) UpdateExpire(ctx context.Context, key interface{}, duration time.Duration) (oldDuration time.Duration, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) GetExpire(ctx context.Context, key interface{}) (time.Duration, error) {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) Remove(ctx context.Context, keys ...interface{}) (lastValue *gvar.Var, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) Clear(ctx context.Context) error {
//TODO implement me
panic("implement me")
}
func (a AdapterElasticsearch) Close(ctx context.Context) error {
//TODO implement me
panic("implement me")
}
func NewAdapterElasticsearch(addresses []string) gcache.Adapter {
return &AdapterElasticsearch{
Addresses: addresses,
}
}

134
pgk/aycache/drive/file.go Normal file
View File

@@ -0,0 +1,134 @@
package drive
import (
"context"
"github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/os/gcache"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/util/gconv"
"path"
"strings"
"time"
)
type AdapterFile struct {
FilePath string
}
func (a AdapterFile) Set(ctx context.Context, key interface{}, value interface{}, duration time.Duration) error {
//defer a.handleLruKey(ctx, key)
//expireTime := a.getInternalExpire(duration)
//a.data.Set(key, memoryDataItem{
// a: value,
// a: expireTime,
//})
//c.eventList.PushBack(&adapterMemoryEvent{
// k: key,
// e: expireTime,
//})
arr := strings.Split(":", gconv.String(key))
fileName := path.Join(arr...)
return gfile.PutBytes(fileName, gconv.Bytes(value))
}
func (a AdapterFile) SetMap(ctx context.Context, data map[interface{}]interface{}, duration time.Duration) error {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) SetIfNotExist(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (ok bool, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) SetIfNotExistFunc(ctx context.Context, key interface{}, f gcache.Func, duration time.Duration) (ok bool, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) SetIfNotExistFuncLock(ctx context.Context, key interface{}, f gcache.Func, duration time.Duration) (ok bool, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) Get(ctx context.Context, key interface{}) (*gvar.Var, error) {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) GetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (result *gvar.Var, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) GetOrSetFunc(ctx context.Context, key interface{}, f gcache.Func, duration time.Duration) (result *gvar.Var, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) GetOrSetFuncLock(ctx context.Context, key interface{}, f gcache.Func, duration time.Duration) (result *gvar.Var, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) Contains(ctx context.Context, key interface{}) (bool, error) {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) Size(ctx context.Context) (size int, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) Data(ctx context.Context) (data map[interface{}]interface{}, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) Keys(ctx context.Context) (keys []interface{}, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) Values(ctx context.Context) (values []interface{}, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) Update(ctx context.Context, key interface{}, value interface{}) (oldValue *gvar.Var, exist bool, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) UpdateExpire(ctx context.Context, key interface{}, duration time.Duration) (oldDuration time.Duration, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) GetExpire(ctx context.Context, key interface{}) (time.Duration, error) {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) Remove(ctx context.Context, keys ...interface{}) (lastValue *gvar.Var, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) Clear(ctx context.Context) error {
//TODO implement me
panic("implement me")
}
func (a AdapterFile) Close(ctx context.Context) error {
//TODO implement me
panic("implement me")
}
func NewAdapterFile(filePath string) gcache.Adapter {
return &AdapterFile{
FilePath: filePath,
}
}

View File

@@ -0,0 +1,15 @@
package drive
import (
"github.com/gogf/gf/v2/os/gcache"
)
var adapterMemoryClient = gcache.New()
// NewAdapterMemory 创建并返回一个新的内存缓存对象。
func NewAdapterMemory() gcache.Adapter {
//if adapterMemoryClient == nil {
// adapterMemoryClient = gcache.New()
//}
return adapterMemoryClient
}

View File

@@ -0,0 +1,120 @@
package drive
import (
"context"
"github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/database/gredis"
"github.com/gogf/gf/v2/os/gcache"
"time"
)
// AdapterRedis is the gcache adapter implements using Redis server.
type AdapterMemcached struct {
//redis *gredis.Redis
//client
}
func (a AdapterMemcached) Set(ctx context.Context, key interface{}, value interface{}, duration time.Duration) error {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) SetMap(ctx context.Context, data map[interface{}]interface{}, duration time.Duration) error {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) SetIfNotExist(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (ok bool, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) SetIfNotExistFunc(ctx context.Context, key interface{}, f gcache.Func, duration time.Duration) (ok bool, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) SetIfNotExistFuncLock(ctx context.Context, key interface{}, f gcache.Func, duration time.Duration) (ok bool, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) Get(ctx context.Context, key interface{}) (*gvar.Var, error) {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) GetOrSet(ctx context.Context, key interface{}, value interface{}, duration time.Duration) (result *gvar.Var, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) GetOrSetFunc(ctx context.Context, key interface{}, f gcache.Func, duration time.Duration) (result *gvar.Var, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) GetOrSetFuncLock(ctx context.Context, key interface{}, f gcache.Func, duration time.Duration) (result *gvar.Var, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) Contains(ctx context.Context, key interface{}) (bool, error) {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) Size(ctx context.Context) (size int, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) Data(ctx context.Context) (data map[interface{}]interface{}, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) Keys(ctx context.Context) (keys []interface{}, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) Values(ctx context.Context) (values []interface{}, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) Update(ctx context.Context, key interface{}, value interface{}) (oldValue *gvar.Var, exist bool, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) UpdateExpire(ctx context.Context, key interface{}, duration time.Duration) (oldDuration time.Duration, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) GetExpire(ctx context.Context, key interface{}) (time.Duration, error) {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) Remove(ctx context.Context, keys ...interface{}) (lastValue *gvar.Var, err error) {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) Clear(ctx context.Context) error {
//TODO implement me
panic("implement me")
}
func (a AdapterMemcached) Close(ctx context.Context) error {
//TODO implement me
panic("implement me")
}
// NewAdapterRedis creates and returns a new memory cache object.
func NewAdapterMemcached(redis *gredis.Redis) gcache.Adapter {
return &AdapterMemcached{}
}

View File

@@ -0,0 +1,18 @@
package drive
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcache"
)
var adapterRedisClient gcache.Adapter
var adapterRedisCache = gcache.New()
func NewAdapterRedis() gcache.Adapter {
if adapterRedisClient == nil {
adapterRedisClient = gcache.NewAdapterRedis(g.Redis("default"))
adapterRedisCache.SetAdapter(adapterRedisClient)
}
return adapterRedisCache
}

19
pgk/notice/notice.go Normal file
View File

@@ -0,0 +1,19 @@
package notice
import (
v1 "github.com/ayflying/utility_go/api/pgk/v1"
"github.com/ayflying/utility_go/pgk/notice/drive"
)
type MessageV1 interface {
Send(value string)
}
func New(typ v1.NoticeType, host string) MessageV1 {
switch typ {
case v1.NoticeType_DINGTALK:
return drive.Load(host)
}
return nil
}

30
pgk/pgk.go Normal file
View File

@@ -0,0 +1,30 @@
package pgk
import (
v1 "github.com/ayflying/utility_go/api/pgk/v1"
"github.com/ayflying/utility_go/pgk/aycache"
"github.com/ayflying/utility_go/pgk/notice"
"github.com/ayflying/utility_go/pgk/rank"
"github.com/ayflying/utility_go/pgk/s3"
"github.com/gogf/gf/v2/os/gcache"
)
var ()
// 统一调用
func Notice(typ v1.NoticeType, host string) notice.MessageV1 {
return notice.New(typ, host)
}
// 统一调用cache
func Cache(_name ...string) gcache.Adapter {
return aycache.New(_name...)
}
func S3(_name ...string) *s3.Mod {
return s3.New(_name...)
}
func Rank() *rank.Mod {
return rank.New()
}

394
pgk/rank/rank.go Normal file
View File

@@ -0,0 +1,394 @@
package rank
import (
"fmt"
v1 "github.com/ayflying/utility_go/api/pgk/v1"
"time"
"github.com/gogf/gf/v2/database/gredis"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gctx"
)
var (
ctx = gctx.New()
)
type Mod struct {
}
type F64CountRank struct {
name string // 排行榜名
updateTs string // 更新时间key
}
//
//type RankData struct {
// Id int64
// Score int64
// Rank int32
// UpdateTs int64
//}
func New() *Mod {
return &Mod{}
}
func (s *Mod) Load() {
}
// CreateF64CountRank 创建一个排行榜实例
// 参数:
//
// name: 排行榜的名称,通常代表一个赛季
//
// 返回值:
//
// *F64CountRank: 返回一个指向新创建的F64CountRank实例的指针
func (s *Mod) CreateF64CountRank(name string) *F64CountRank {
// 初始化F64CountRank实例的name和updateTs字段
// name字段用于标识排行榜的名称格式为"rank:<name>:score"
// updateTs字段用于标识排行榜的更新时间格式为"rank:<name>:updateTs"
return &F64CountRank{
name: fmt.Sprintf("rank:%s:score", name),
updateTs: fmt.Sprintf("rank:%s:updateTs", name),
}
}
// IncrScore 对指定ID的分数进行增加并返回增加后的当前分数。
// 该方法首先更新成员的更新时间戳,然后增加成员的分数。
//
// 参数:
//
// id - 要操作的成员ID。
// score - 要增加的分数。
//
// 返回值:
//
// curScore - 增加分数后的当前分数。
// err - 操作过程中可能发生的错误。
//
// IncrScore 先改redis再改cache
//
// @Description:
// @receiver r
// @param id
// @param score
// @return curScore
// @return err
func (r *F64CountRank) IncrScore(id int64, score int64) (curScore float64, err error) {
// 记录当前时间戳,用于更新成员的最新活动时间。
now := time.Now().UnixMilli()
// 将成员的更新时间戳加入到Redis的有序集合中确保成员的排序依据是最新的活动时间。
_, err = g.Redis().ZAdd(ctx, r.updateTs, &gredis.ZAddOption{}, gredis.ZAddMember{
Score: float64(now),
Member: id,
})
// 增加成员的分数,并返回增加后的当前分数。
curScore, err = g.Redis().ZIncrBy(ctx, r.name, float64(score), id)
//如果分数小于0则删除
if curScore <= 0 {
err = r.DelScore(id)
}
return
}
// todo暂时未使用
func (r *F64CountRank) GetCount() {
count, _ := g.Redis().ZCard(ctx, r.name)
if count > 9999 {
//删除超过9999的数据
g.Redis().ZRemRangeByRank(ctx, r.name, 0, -9999)
}
}
// Delete 删除当前排行榜
// 该方法通过删除Redis中与排行榜相关的键来清除排行榜信息
func (r *F64CountRank) Delete() {
// 删除排行榜数据键
_, err := g.Redis().Del(ctx, r.name)
if err != nil {
// 如果删除失败,记录错误日志
g.Log().Error(ctx, "排行榜删除失败:%v", err)
}
// 删除排行榜更新时间键
_, err = g.Redis().Del(ctx, r.updateTs)
if err != nil {
// 如果删除失败,记录错误日志
g.Log().Error(ctx, "排行榜删除失败:%v", err)
}
}
// DelScore 删除当前分数
//
// 该方法从更新时间有序集合和排名有序集合中移除指定的id。
// 这通常用于从排行榜中删除一个条目,同时确保其在更新时间集合中的对应记录也被清除。
//
// @Description: 从更新时间和排名集合中移除指定id
// @receiver r 接收者为F64CountRank类型的实例
// @param id 要从集合中移除的条目的ID
// @return err 可能发生的错误如果操作成功err为nil
func (r *F64CountRank) DelScore(id int64) (err error) {
// 从更新时间集合中移除id
_, err = g.Redis().ZRem(ctx, r.updateTs, id)
// 从排名集合中移除id
_, err = g.Redis().ZRem(ctx, r.name, id)
return
}
// DelByRank 根据排名范围删除元素。
// 该方法使用了Redis的有序集合数据结构通过ZRange和ZRemRangeByRank命令来实现。
// 参数start和stop定义了要删除的排名范围从start到stop包括start和stop
// 返回可能的错误。
func (r *F64CountRank) DelByRank(start int64, stop int64) (err error) {
// 初始化一个空的int64切片用于存储指定排名范围内的元素。
var members []int64
// 使用Redis的ZRange命令获取指定排名范围内的元素。
// 选项Rev设置为true表示按照分数从高到低的顺序返回元素。
get, err := g.Redis().ZRange(ctx, r.name, start, stop,
gredis.ZRangeOption{
Rev: true,
})
// 使用Scan方法将获取到的元素扫描到members切片中。
err = get.Scan(&members)
// 如果扫描过程中出现错误,直接返回错误。
if err != nil {
return
}
// 遍历members切片对于每个元素使用ZRem命令从更新时间集合中删除对应的成员。
for _, member := range members {
_, err = g.Redis().ZRem(ctx, r.updateTs, member)
// 忽略ZRem操作的错误因为即使元素不存在ZRem也不会返回错误。
}
// 使用ZRemRangeByRank命令从有序集合中删除指定排名范围内的元素。
_, err = g.Redis().ZRemRangeByRank(ctx, r.name, start, stop)
// 返回可能的错误。
return
}
// updateScore 更新给定ID的分数值。
//
// 参数:
//
// id - 需要更新分数的实体ID。
// score - 新的分数值。
//
// 返回值:
//
// error - 更新过程中可能出现的错误。
//
// 该方法首先记录当前时间作为更新时间戳,然后将新的分数值添加到排名系统中。
// 使用Redis的ZAdd方法来确保操作的原子性和一致性。
// UpdateScore 更新分数
//
// @Description:
// @receiver r
// @param id
// @param score
// @return err
func (r *F64CountRank) UpdateScore(id int64, score int64) (err error) {
// 获取当前时间戳,以毫秒为单位。
now := time.Now().UnixMilli()
// 向更新时间戳的有序集合中添加新的成员和分数成员为id分数为当前时间戳。
_, err = g.Redis().ZAdd(ctx, r.updateTs, &gredis.ZAddOption{}, gredis.ZAddMember{
Score: float64(now),
Member: id,
})
// 向排名的有序集合中添加新的成员和分数成员为id分数为传入的score。
_, err = g.Redis().ZAdd(ctx, r.name, &gredis.ZAddOption{}, gredis.ZAddMember{
Score: float64(score),
Member: id,
})
return
}
//// GetRankInfosV1 获取0~count跳记录
//func (r *F64CountRank) getRankInfosV1(offset, count int) (list []*RankInfo, err error) {
// /*
// 找到maxRank的玩家的分数
// 根据分数拿到所有分数大于等于minScore玩家
// 将这些玩家进行排序
// 返回maxRank条目
// */
// var (
// minScore int64 // 最低分
// maxScore int64
// //zl []redis2.Z
// zl []gredis.ZAddMember
// length int
// )
// // 拉取所有玩家的更新时间戳
// zl, err = g.Redis().ZRemRangeByScore(ctx,r.updateTs, strconv.Itoa(0), strconv.Itoa(-1))//ZRemRangeByScore(ctx, r.updateTs, strconv.Itoa(0), strconv.Itoa(-1))
// //zl, err = rdbV1.ZRangeWithScores(ctx, r.updateTs, 0, -1).Result()
// if err != nil {
// g.Log().Errorf(ctx, "redis err:%v", err)
// return
// }
// if len(zl) == 0 {
// //logs.Infof("empty list")
// return
// }
// tsl := make(map[int64]int64, len(zl))
// for _, z := range zl {
// id := gconv.Int64(z.Member) //pgk.InterfaceToNumber[uint64](z.Member)
// tsl[id] = int64(z.Score)
// }
//
// // 找到maxRank的玩家的分数
// zl, err = rdbV1.ZRevRangeByScoreWithScores(ctx, r.name, &redis2.ZRangeBy{
// Min: "0",
// Max: strconv.Itoa(math.MaxInt),
// Offset: 0,
// Count: int64(count),
// }).Result()
// if err != nil {
// g.Log().Errorf(ctx, "redis err:%v", err)
// return
// }
// if len(zl) == 0 {
// g.Log().Info(ctx, "empty list")
// return
// }
// minScore = int64(zl[len(zl)-1].Score)
// maxScore = int64(zl[0].Score)
// // 根据分数拿到所有分数大于等于minScore玩家
// zl, err = rdbV1.ZRevRangeByScoreWithScores(ctx, r.name, &redis2.ZRangeBy{
// Min: fmt.Sprintf("%v", minScore),
// Max: fmt.Sprintf("%v", maxScore),
// }).Result()
// if err != nil {
// g.Log().Errorf(ctx, "redis err:%v", err)
// return
// }
// if len(zl) == 0 {
// g.Log().Info(ctx, "empty list")
// return
// }
// //如果开始已经大于等于总长度,就返回空
// if offset >= len(zl) {
// return
// }
// list = make([]*RankInfo, len(zl))
// for i, z := range zl {
// id := gconv.Int64(z.Member)
// list[i] = &RankInfo{
// Id: id,
// Score: int64(z.Score),
// UpdateTs: tsl[id],
// }
// }
// // 将这些玩家进行排序
// sort.Slice(list, func(i, j int) bool {
// if list[i].Score != list[j].Score {
// return list[i].Score > list[j].Score
// } else {
// return list[i].UpdateTs < list[j].UpdateTs
// }
// })
// length = len(list)
// if length > count {
// length = count
// }
// for i := range list {
// info := list[i]
// info.Rank = i + 1
// }
//
// list = list[offset:length]
// return
//}
// GetRankInfosNotTs 获取0~count跳记录 不根据更新时间来
// 该方法使用ZRange命令从Redis中获取指定范围的排名信息不考虑更新时间
// 参数:
//
// offset - 获取记录的起始偏移量
// count - 获取记录的数量
//
// 返回值:
//
// list - 排名信息列表
// err - 错误信息,如果执行过程中遇到错误
func (r *F64CountRank) GetRankInfosNotTs(offset, count int) (list []*v1.RankData, err error) {
// 初始化存储成员ID的切片
var members []int64
// 使用Redis的ZRange命令获取指定范围的成员ID
// 参数Rev设为true以从高分到低分获取成员
get, err := g.Redis().ZRange(ctx, r.name, int64(offset), int64(count),
gredis.ZRangeOption{
Rev: true,
}) //.ScanSlice(&members)
// 将获取的结果扫描到members切片中
err = get.Scan(&members)
// 如果发生错误,记录日志并返回
if err != nil {
//logs.Withf("redis err:%v", err)
return
}
// 根据获取的成员ID数量初始化排名信息列表
list = make([]*v1.RankData, len(members))
for i := range members {
// 获取当前成员ID
id := members[i]
// 使用成员ID获取排名信息不考虑更新时间
list[i] = r.GetIdRankNotTs(id)
}
// 返回排名信息列表和可能的错误
return
}
// GetIdRankNotTs 获取指定id的当前排名
// 该方法从Redis的有序集合中查询指定id的分数和排名信息不考虑时间戳
// 参数:
//
// id - 需要查询排名的id
//
// 返回值:
//
// rankInfo - 包含id的分数和排名信息的指针如果没有找到则返回nil
func (r *F64CountRank) GetIdRankNotTs(id int64) (rankInfo *v1.RankData) {
// 初始化rankInfo结构体设置id其他字段将通过查询填充
rankInfo = &v1.RankData{Id: id}
// 查询有序集合中指定id的分数
score, err := g.Redis().ZScore(ctx, r.name, id)
if err != nil {
// 如果发生错误直接返回rankInfo为初始化状态Id已设置其他字段为零值
return
}
// 将分数转换为int64类型并更新rankInfo
rankInfo.Score = int64(score)
// 如果分数为0直接返回表示该id的分数为0没有进一步查询排名的必要
if score == 0 {
return
}
// 查询有序集合中指定id的排名
rank, err := g.Redis().ZRevRank(ctx, r.name, id)
if err != nil {
// 如果发生错误直接返回rankInfo中仅分数有效排名信息未更新
return
}
// 更新rankInfo中的排名信息排名从0开始所以需要加1以符合人类的计数习惯
rankInfo.Rank = int32(rank) + 1
// 返回包含完整排名信息的rankInfo指针
return rankInfo
}

289
pgk/s3/s3.go Normal file
View File

@@ -0,0 +1,289 @@
package s3
import (
"fmt"
"io"
"log"
"net/url"
"path"
"time"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcache"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/util/gconv"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
var (
//client *minio.Client
ctx = gctx.New()
)
type DataType struct {
AccessKey string `json:"access_key"`
SecretKey string `json:"secret_key"`
Address string `json:"address"`
Ssl bool `json:"ssl"`
Url string `json:"url"`
BucketName string `json:"bucket_name"`
BucketNameCdn string `json:"bucket_name_cdn"`
}
type Mod struct {
client *minio.Client
cfg DataType
}
func New(_name ...string) *Mod {
var name string
if len(_name) > 0 {
name = _name[0]
} else {
getName, _ := g.Cfg().Get(ctx, "s3.type")
name = getName.String()
}
get, err := g.Cfg().Get(ctx, "s3."+name)
if err != nil {
panic(err.Error())
}
var cfg DataType
get.Scan(&cfg)
// 使用minio-go创建S3客户端
obj, err := minio.New(
cfg.Address,
&minio.Options{
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
Secure: cfg.Ssl,
},
)
if err != nil {
log.Fatalln(err)
}
mod := &Mod{
client: obj,
cfg: cfg,
}
return mod
}
//func (s *Mod) Load() {
// //导入配置
// get, err := g.Cfg().Get(ctx, "s3.type")
// cfgType := get.String()
// if cfgType == "" {
// cfgType = "default"
// }
//
// cfgData, err := g.Cfg().Get(ctx, "s3."+cfgType)
// if cfgData.IsEmpty() {
// panic("当前配置中未配置s3" + cfgType)
// }
//
// get, err = g.Cfg().Get(ctx, "s3."+cfgType)
// err = get.Scan(&Cfg)
//
// // 使用minio-go创建S3客户端
// obj, err := minio.New(
// Cfg.Address,
// &minio.Options{
// Creds: credentials.NewStaticV4(Cfg.AccessKey, Cfg.SecretKey, ""),
// Secure: Cfg.Ssl,
// },
// )
// if err != nil {
// log.Fatalln(err)
// }
//
// client = obj
//}
//
//func (s *Mod) S3(name string) {
// get, err := g.Cfg().Get(ctx, "s3."+name)
// if err != nil {
// panic(err)
// }
// get.Scan(&Cfg)
//
// // 使用minio-go创建S3客户端
// obj, err := minio.New(
// Cfg.Address,
// &minio.Options{
// Creds: credentials.NewStaticV4(Cfg.AccessKey, Cfg.SecretKey, ""),
// Secure: Cfg.Ssl,
// },
// )
// if err != nil {
// log.Fatalln(err)
// }
//
// client = obj
//
//}
// GetCfg 获取配置
func (s *Mod) GetCfg() *DataType {
return &s.cfg
}
// GetFileUrl 生成指向S3存储桶中指定文件的预签名URL
//
// @Description: 生成一个具有有限有效期的预签名URL可用于访问S3存储桶中的文件。
// @receiver s: S3的实例用于执行S3操作。
// @param name: 要获取预签名URL的文件名。
// @param bucketName: 文件所在的存储桶名称。
// @return presignedURL: 生成的预签名URL可用于访问文件。
// @return err: 在获取预签名URL过程中遇到的任何错误。
func (s *Mod) GetFileUrl(name string, bucketName string, _expires ...time.Duration) (presignedURL *url.URL, err error) {
// 设置预签名URL的有效期为1小时
expires := time.Hour * 1
if len(_expires) > 0 {
expires = _expires[0]
}
cacheKey := fmt.Sprintf("s3:%v:%v", name, bucketName)
get, _ := gcache.Get(ctx, cacheKey)
//g.Dump(get.Vars())
if !get.IsEmpty() {
err = gconv.Struct(get.Val(), &presignedURL)
//presignedURL =
return
}
//expires := time.Duration(604800)
// 调用s3().PresignedGetObject方法生成预签名URL
presignedURL, err = s.client.PresignedGetObject(ctx, bucketName, name, expires, nil)
err = gcache.Set(ctx, cacheKey, presignedURL, expires)
return
}
// PutFileUrl 生成一个用于上传文件到指定bucket的预签名URL
//
// @Description:
// @receiver s
// @param name 文件名
// @param bucketName 存储桶名称
// @return presignedURL 预签名的URL用于上传文件
// @return err 错误信息如果在生成预签名URL时发生错误
func (s *Mod) PutFileUrl(name string, bucketName string) (presignedURL *url.URL, err error) {
// 设置预签名URL的有效期
//expires := time.Now().Add(time.Minute * 30).Unix() // 例如有效期30分钟
//expires2 := time.Duration(expires)
expires := time.Minute * 10
// 生成预签名URL
presignedURL, err = s.client.PresignedPutObject(ctx, bucketName, name, expires)
return
}
// 获取储存桶列表
func (s *Mod) ListBuckets() []minio.BucketInfo {
buckets, err := s.client.ListBuckets(ctx)
//g.Dump(buckets)
if err != nil {
//fmt.Println(err)
return nil
}
return buckets
}
// PutObject 上传文件到指定的存储桶中。
//
// @Description: 上传一个文件到指定的存储桶。
// @receiver s *Mod: 表示调用此方法的Mod实例。
// @param f io.Reader: 文件的读取器,用于读取待上传的文件内容。
// @param name string: 待上传文件的名称。
// @param bucketName string: 存储桶的名称。
// @param _size ...int64: 可选参数,指定上传文件的大小。如果未提供,则默认为-1表示读取文件直到EOF。
// @return res minio.UploadInfo: 上传成功后返回的上传信息。
// @return err error: 如果上传过程中出现错误,则返回错误信息。
func (s *Mod) PutObject(f io.Reader, name string, bucketName string, _size ...int64) (res minio.UploadInfo, err error) {
// 初始化文件大小为-1表示将读取文件至结束。
var size = int64(-1)
// 如果提供了文件大小,则使用提供的大小值。
if len(_size) > 0 {
size = _size[0]
}
// 调用client的PutObject方法上传文件并设置内容类型为"application/octet-stream"。
res, err = s.client.PutObject(ctx, bucketName, name, f, size, minio.PutObjectOptions{ContentType: "application/octet-stream"})
if err != nil {
g.Log().Error(ctx, err)
}
return
}
// RemoveObject 删除文件
func (s *Mod) RemoveObject(name string, bucketName string) (err error) {
opts := minio.RemoveObjectOptions{
//GovernanceBypass: true,
//VersionID: "myversionid",
}
err = s.client.RemoveObject(ctx, bucketName, name, opts)
return
}
// ListObjects 文件列表
func (s *Mod) ListObjects(bucketName string, prefix string) (res <-chan minio.ObjectInfo, err error) {
res = s.client.ListObjects(ctx, bucketName, minio.ListObjectsOptions{
Prefix: prefix,
})
return
}
// SetBucketPolicy 设置bucket或对象前缀的访问权限
func (s *Mod) SetBucketPolicy(bucketName string, prefix string) (err error) {
policy := `{"Version": "2012-10-17","Statement": [{"Action": ["s3:GetObject"],"Effect": "Allow","Principal": {"AWS": ["*"]},"Resource": ["arn:aws:s3:::my-bucketname/*"],"Sid": ""}]}`
err = s.client.SetBucketPolicy(ctx, bucketName, policy)
return
}
// GetUrl 获取文件访问地址
func (s *Mod) GetUrl(filePath string, defaultFile ...string) (url string) {
bucketName := s.cfg.BucketNameCdn
get := s.cfg.Url
//如果没有图片,返回默认的图片地址
if filePath == "" && len(defaultFile) > 0 {
filePath = defaultFile[0]
}
if s.cfg.Ssl {
url = get + filePath
} else {
url = get + path.Join(bucketName, filePath)
}
return
}
func (s *Mod) GetPath(url string) (filePath string) {
bucketName := s.cfg.BucketNameCdn
get := s.cfg.Url
return url[len(get+bucketName)+1:]
}
// 复制文件
func (s *Mod) CopyObject(bucketName string, dstStr string, srcStr string) (err error) {
// 原始文件
var dst = minio.CopyDestOptions{
Bucket: bucketName,
Object: dstStr,
}
// 新文件
var src = minio.CopySrcOptions{
Bucket: bucketName,
Object: srcStr,
}
_, err = s.client.CopyObject(ctx, dst, src)
return
}