完成框架搭建

master
徐俊杰 3 months ago
parent d082f72b1a
commit 166e837217

3
.gitignore vendored

@ -1,2 +1,3 @@
*/.idea */.idea
*/.vscode */.vscode
*.exe

8
.idea/.gitignore vendored

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

@ -0,0 +1,9 @@
<?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>

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

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

@ -0,0 +1,15 @@
FROM busybox:glibc
COPY ./docs/Shanghai /usr/share/zoneinfo/Asia/Shanghai
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone
COPY conf/certs /etc/ssl/certs
#ENV TZ Asia/Shanghai
WORKDIR /app/main-client
#通过名称引用
COPY ./build/app ./bin/mainServer
COPY ./conf/ /app/conf/
COPY ./conf/ ./conf/
WORKDIR /app/main-client/bin
CMD ["./mainServer"]

@ -0,0 +1,16 @@
FROM busybox:glibc
COPY ./conf/Shanghai /usr/share/zoneinfo/Asia/Shanghai
COPY conf/certs /etc/ssl/certs
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone
#ENV TZ Asia/Shanghai
ENV MODE_ENV test
WORKDIR /app/main-client
#通过名称引用
COPY ./build/container-dev ./bin/mainServer
COPY ./conf/test /app/conf/
COPY ./conf/test ./conf/
COPY ./conf/imageCreatedAt ./conf/
WORKDIR /app/main-client/bin
CMD ["./mainServer"]

@ -0,0 +1,53 @@
package main
import (
"dubbo.apache.org/dubbo-go/v3/common/logger"
"fmt"
"github.com/fonchain/fonchain-container/cmd/internal/controller"
sysconf "github.com/fonchain/fonchain-container/pkg/config"
"github.com/fonchain/fonchain-container/pkg/ticker"
"os"
"dubbo.apache.org/dubbo-go/v3/config"
_ "dubbo.apache.org/dubbo-go/v3/imports"
"github.com/fonchain/fonchain-container/pkg/cache"
db "github.com/fonchain/fonchain-container/pkg/db"
"github.com/fonchain/fonchain-container/pkg/m"
_ "github.com/fonchain/fonchain-container/pkg/service" //重要导入
)
// export DUBBO_GO_CONFIG_PATH= PATH_TO_SAMPLES/helloworld/go-server/conf/dubbogo.yaml
func main() {
if err := sysconf.LoadConfig(m.SERVER_CONFIG); err != nil {
panic(err.Error())
}
db.Init(m.SERVER_CONFIG)
fmt.Println("redis配置")
cache.InitRedis(m.SERVER_CONFIG)
fmt.Println("注入provider")
//加载微服务
config.SetProviderService(&controller.ContainerProvider{})
fmt.Println("开始配置文件")
if err := config.Load(); err != nil {
panic(err)
}
logger.Info("开始配置文件end")
//打印镜像构建时间
printImageBuildDateFromFile()
//定时任务,循环时间是写死的
go ticker.SimpleRunTimerTask()
select {}
}
func printImageBuildDateFromEnv() {
buildDate := os.Getenv("BUILD_DATE")
fmt.Println("镜像生成时间:", buildDate)
}
func printImageBuildDateFromFile() {
buildDate, _ := os.ReadFile("../conf/imageCreatedAt")
fmt.Println("镜像生成时间:", string(buildDate))
}

@ -0,0 +1,15 @@
// Package controller -----------------------------
// @file : container.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2024/7/2 上午11:43
// -------------------------------------------
package controller
type ContainerProvider struct {
}
func (c ContainerProvider) mustEmbedUnimplementedContainerServer() {
//TODO implement me
panic("implement me")
}

@ -7,8 +7,8 @@
package tcp package tcp
import ( import (
"esp8266Server/tcp/message"
"fmt" "fmt"
message2 "github.com/fonchain/fonchain-container/cmd/internal/embedded/implement/tcp/message"
"net" "net"
"sync" "sync"
) )
@ -91,11 +91,11 @@ func (c *ClientRoom) SendMsg(mchId, msg string) error {
return nil return nil
} }
func (c *ClientRoom) HandleMsg(msg []byte) { func (c *ClientRoom) HandleMsg(msg []byte) {
mb := message.CommonType(msg) mb := message2.CommonType(msg)
fmt.Println("接收消息", mb.GetFull()) fmt.Println("接收消息", mb.GetFull())
switch mb.GetCmd() { switch mb.GetCmd() {
case "002": case "002":
pingMb := message.PingType(msg) pingMb := message2.PingType(msg)
fmt.Printf("获取pong消息: [mchId:%s] [body:%s]\n", pingMb.GetMchId(), pingMb.GetBody()) fmt.Printf("获取pong消息: [mchId:%s] [body:%s]\n", pingMb.GetMchId(), pingMb.GetBody())
default: default:
fmt.Printf("未知命令[%s] ,[mchId:%s] [body:%s]\n", mb.GetCmd(), mb.GetMchId(), mb.GetBody()) fmt.Printf("未知命令[%s] ,[mchId:%s] [body:%s]\n", mb.GetCmd(), mb.GetMchId(), mb.GetBody())

@ -8,8 +8,8 @@ package tcp
import ( import (
"context" "context"
"esp8266Server/tcp/message"
"fmt" "fmt"
"github.com/fonchain/fonchain-container/cmd/internal/embedded/implement/tcp/message"
"log" "log"
"net" "net"
"time" "time"

@ -0,0 +1,11 @@
// Package hardware -----------------------------
// @file : ws281x.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2024/7/1 上午11:45
// -------------------------------------------
package implement
// ws81x系统LED灯带控制驱动
type Ws281x struct {
}

@ -0,0 +1,12 @@
// Package hardware -----------------------------
// @file : interface.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2024/7/1 上午11:40
// -------------------------------------------
package embedded
type ILEDDriver interface {
Ping()
LEDSet()
}

@ -0,0 +1,20 @@
// Package model -----------------------------
// @file : boxRelPin.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2024/7/1 下午3:06
// -------------------------------------------
package model
type BoxRelPin struct {
Model
DeviceSn string `gorm:"column:device_sn;comment:硬件设备序列号"`
BoxId int `gorm:"column:box_id;comment:盒子ID"`
PinId int `gorm:"column:pin_id;comment:引脚ID"`
DevicePin *DevicePin `gorm:"foreignKey:PinId;"`
Color string `gorm:"column:color;default:;comment:颜色 r,g,b,y,*"`
}
func (d BoxRelPin) TableName() string {
return "box_rel_pin"
}

@ -0,0 +1,54 @@
// Package model -----------------------------
// @file : container.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2024/7/1 上午11:47
// -------------------------------------------
package model
import (
"github.com/fonchain/fonchain-container/pkg/util"
"gorm.io/gorm"
)
// Container 货柜
type Container struct {
Model
ContainerUid string `gorm:"column:container_uid;comment:货柜编号"`
Name string `gorm:"column:name;comment:货柜名称"`
ColumnLen int `gorm:"column:column_len;comment:货柜列数"`
RowLen int `gorm:"column:row_len;comment:货柜行数"`
}
func (c Container) TableName() string {
return "container"
}
func (c *Container) BeforeCreate(tx *gorm.DB) (err error) {
if c.ContainerUid == "" {
c.ContainerUid, err = util.GetUid()
}
return nil
}
// func (d *Device) BeforeCreate(tx *gorm.DB) error {
// // 获取当前日期格式化为yyMMdd
// currentDate := time.Now().Format(stime.Format_NoSpacer_YMD)
//
// // 生成一个4位的随机序列号范围0000-9999
// randomSeq := fmt.Sprintf("%04d", rand.Intn(10000))
//
// // 构造SN号主体部分
// sn := currentDate + productCode + randomSeq
//
// // 计算校验位这里简单使用所有字符ASCII值之和对11取模
// var checkSum int
// for _, char := range sn {
// checkSum += int(char)
// }
// checkSum %= 11
// checkSumStr := fmt.Sprintf("%01d", checkSum)
//
// // 返回完整的SN号包括校验位
// d.SN = sn + checkSumStr
// return nil
// }

@ -0,0 +1,25 @@
// Package model -----------------------------
// @file : containerBox.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2024/7/1 下午3:02
// -------------------------------------------
package model
type ContainerBox struct {
Model
ContainerUid string `gorm:"column:container_uid;comment:容器编号"`
BoxName string `gorm:"column:box_name;comment:箱子名称"`
Profundity string `gorm:"column:profundity;comment:孔深单位cm"`
//ArtworkUid string `gorm:"column:artwork_uid;comment:艺术品编号"` //这个应该关联画筒
RelPin []*BoxRelPin `gorm:"foreignKey:BoxId;references:id"`
Tags []*Tag `gorm:"many2many:box_tag_rel;"`
Enable int `gorm:"column:enable;default:1;comment:是否启用 1=启用中 2=未启用"`
OperationTime string `gorm:"column:operation_time;comment:操作时间"`
OperatorName string `gorm:"column:operator_name;comment:操作人"`
OperatorAccount string `gorm:"column:operator_account;comment:操作人账号"`
}
func (b ContainerBox) TableName() string {
return "container_box"
}

@ -0,0 +1,19 @@
// Package model -----------------------------
// @file : device.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2024/7/1 下午3:03
// -------------------------------------------
package model
type Device struct {
Model
SN string `gorm:"column:sn;comment:硬件设备序列号"`
Location string `gorm:"column:location;comment:所在位置"`
NetStatus int `gorm:"column:net_status;default:2;comment:联网状态 1=在线 2=离线"`
UseStatus int `gorm:"column:use_status;default:1;comment:设备状态 1=使用中 2=作废"`
}
func (d Device) TableName() string {
return "device"
}

@ -0,0 +1,18 @@
// Package model -----------------------------
// @file : devicePin.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2024/7/1 下午3:05
// -------------------------------------------
package model
type DevicePin struct {
Model
DeviceSN string `gorm:"column:device_sn;comment:硬件设备序列号"`
PinNo int `gorm:"column:pin_no;comment:引脚号/led索引位"`
Status int `gorm:"column:status;default:1;comment:引脚状态 1=未使用 2=已使用 3=损坏"`
}
func (d DevicePin) TableName() string {
return "device_pin"
}

@ -0,0 +1,13 @@
package model
import (
"gorm.io/plugin/soft_delete"
"time"
)
type Model struct {
ID int64 `gorm:"primarykey;" json:"id" form:"id"`
CreatedAt time.Time `gorm:"column:created_at" json:"createdAt"`
UpdatedAt time.Time `gorm:"column:updated_at" json:"updatedAt"`
DeletedAt soft_delete.DeletedAt `gorm:"column:deleted_at;type:bigint" json:"deletedAt"`
}

@ -0,0 +1,23 @@
// Package model -----------------------------
// @file : operationRecord.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2024/7/1 下午4:10
// -------------------------------------------
package model
type OperationRecord struct {
Model
Menu string `gorm:"column:menu;comment:菜单"`
View string `gorm:"column:view;comment:页面"`
Action string `gorm:"column:action;comment:操作"`
Detail string `gorm:"column:detail;comment:操作详情"`
Remark string `gorm:"column:remark;comment:备注"`
OperationTime string `gorm:"column:operation_time;comment:操作时间"`
OperatorName string `gorm:"column:operator_name;comment:操作人"`
OperatorAccount string `gorm:"column:operator_account;comment:操作人账号"`
}
func (o OperationRecord) TableName() string {
return "operation_record"
}

@ -0,0 +1,16 @@
// Package model -----------------------------
// @file : tag.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2024/7/1 下午4:03
// -------------------------------------------
package model
type Tag struct {
Model
Name string `gorm:"column:name;comment:"`
}
func (t *Tag) TableName() string {
return "tag"
}

@ -0,0 +1,3 @@
{"level":"\u001b[31mERROR\u001b[0m","time":"2024-07-02T11:51:39.471+0800","caller":"common/rpc_service.go:259","message":"type com.fontree.microservices.common.Container has no exported methods of suitable type"}
{"level":"\u001b[31mERROR\u001b[0m","time":"2024-07-02T11:51:39.472+0800","caller":"config/service_config.go:238","message":"The service com.fontree.microservices.common.Container export the protocol tri error! Error message is type com.fontree.microservices.common.Container has no exported methods of suitable type."}
{"level":"\u001b[31mERROR\u001b[0m","time":"2024-07-02T11:51:39.472+0800","caller":"config/provider_config.go:149","message":"service ContainerProvider export failed! err: The service com.fontree.microservices.common.Container export the protocol tri error! Error message is type com.fontree.microservices.common.Container has no exported methods of suitable type."}

@ -0,0 +1,30 @@
[system]
mode = dev #正式prod #测试dev
JaegerHost="172.16.100.99:6831"
[mysql]
Db = mysql
DbHost = 127.0.0.1
DbPort = 3306
DbUser = root
DbPassWord = "123456"
DbName = container
[redis]
RedisDB = 2
RedisAddr = 127.0.0.1:6379
#RedisPW = "nDCTrfTtBu3Pw"
#RedisDBNAme =
[chain]
IP=127.0.0.1:37101
MnemonicWords=知 睡 迷 纤 纲 耀 镜 婆 渡 考 拔 百
ContractAccount=XC8214684261867838@xuper
ContractName=fp001
[zap_log]
level: "info"
filename: "logs/container.log"
max_size: 200
max_age: 30
max_backups: 7

@ -0,0 +1,65 @@
dubbo:
metrics:
enable: true # default is true
path: /metrics # default is /metrics
port: 9091 # default is 9090
namespace: dubboArtist # default is dubbo 作为数据上报 metrics 的前
registries:
demoZK:
protocol: zookeeper
timeout: 3s
address: 127.0.0.1:2181
# address: 121.229.45.214:9004
# address: 114.218.158.24:2181
# address: 172.16.100.93:2181
protocols:
triple: #triple
name: tri
# ip: 121.229.45.214
port: 20005
provider:
filter: tracing
services:
ContainerProvider:
interface: com.fontree.microservices.common.Container
retries: 0
logger:
zap-config:
level: error # 日志级别
development: false
disableCaller: false
disableStacktrace: false
encoding: "json"
# zap encoder 配置
encoderConfig:
messageKey: "message"
levelKey: "level"
timeKey: "time"
nameKey: "logger"
callerKey: "caller"
stacktraceKey: "stacktrace"
lineEnding: ""
levelEncoder: "capitalColor"
timeEncoder: "iso8601"
durationEncoder: "seconds"
callerEncoder: "short"
nameEncoder: ""
EncodeTime: zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.000"),
EncodeDuration: zapcore.SecondsDurationEncoder,
outputPaths:
- "stderr"
errorOutputPaths:
- "stderr"
lumberjack-config:
# 写日志的文件名称
filename: "runtime/logs/artist_server.log"
# 每个日志文件长度的最大大小,单位是 MiB。默认 100MiB
maxSize: 10
# 日志保留的最大天数(只保留最近多少天的日志)
maxAge: 15
# 只保留最近多少个日志文件,用于控制程序总日志的大小
maxBackups: 10
# 是否使用本地时间,默认使用 UTC 时间
localTime: true
# 是否压缩日志文件,压缩方法 gzip
compress: false

@ -0,0 +1,39 @@
[system]
mode = prod #正式prod #测试dev
config_source = configmap
[mysql]
DbHost = ${artist.mysql.host|localhost}
DbPort = ${artist.mysql.port|3306}
DbUser = artuser
DbPassWord = "C250PflXIWv2SQm8"
DbArtist = ${artist.mysql.db_name}
[redis]
RedisDB = ${artist.redis.db}
RedisAddr = ${artist.redis.addr}
RedisPW = "nDCTrfTtBu3Pw"
RedisDBNAme =
[zap_log]
level= ${artist.zap.level}
filename = ${artist.zap.filename}
max_size = ${zap.max_size}
max_age = ${zap.max_age}
max_backups = ${zap.max_backups}
[jaeger]
jaeger_host = ${jaeger.host}
jaeger_open = ${artist.jaeger_open}
[rabbitmq]
user: "myuser"
password: "mypass"
host: "172.16.100.93"
port: 9053
vhost_artist= ${artist.rabbitmq.vhost}
vhost_process_data= "process_data"
[baidu]
ak = "SjscdLEybzyxiV7lXKA5iSvZ"
sk = "22fCduMdCarO6WWOi4WiSmt9rIeez3FW"

@ -0,0 +1,89 @@
dubbo:
metrics:
enable: true # default is true
path: /metrics # default is /metrics
port: 9091 # default is 9090
namespace: dubboArtist # default is dubbo 作为数据上报 metrics 的前缀
registries:
demoZK:
protocol: zookeeper
address: zk-cs:2181
# protocol: nacos
# address: 127.0.0.1:8848
# username: "dyb"
# password: "rootdyb"
# namespace: "4684d3a3-165f-4218-8ab8-f4fa03c8efe0"
# group: GROUP_AERTIST
# data_id: com.fontree.microservices.common.Artist
# tracing:
# mytracingKey:
# address: "http://tracing-analysis-dc-hz.aliyuncs.com/XXXXXX/api/traces"
protocols:
triple: #triple
name: tri
port: 20004
provider:
filter: tracing
services:
ArtistProvider:
interface: com.fontree.microservices.common.Artist
retries: 0
# filter: myServerFilter
# application: "1234"
filter: tps,tracing
tps.limiter: method-service
tps.limit.strategy: fixedWindow
tps.limit.rejected.handler: DefaultValueHandler
tps.limit.interval: 1000
tps.limit.rate: 3000
warmup: 100 #预热时间
ArtistThirdPartyProvider:
interface: com.fontree.microservices.common.ArtistThirdParty
retries: 0
filter: tps,tracing
tps.limiter: method-service
tps.limit.strategy: fixedWindow
tps.limit.rejected.handler: DefaultValueHandler
tps.limit.interval: 1000
tps.limit.rate: 3000
warmup: 100 #预热时间
logger:
zap-config:
level: info # 日志级别
development: false
disableCaller: false
disableStacktrace: false
encoding: "json"
# zap encoder 配置
encoderConfig:
messageKey: "message"
levelKey: "level"
timeKey: "time"
nameKey: "logger"
callerKey: "caller"
stacktraceKey: "stacktrace"
lineEnding: ""
levelEncoder: "capitalColor"
timeEncoder: "iso8601"
durationEncoder: "seconds"
callerEncoder: "short"
nameEncoder: ""
EncodeTime: zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.000"),
EncodeDuration: zapcore.SecondsDurationEncoder,
outputPaths:
- "stderr"
errorOutputPaths:
- "stderr"
lumberjack-config:
# 写日志的文件名称
filename: "runtime/logs/artist_server.log"
# 每个日志文件长度的最大大小,单位是 MiB。默认 100MiB
maxSize: 10
# 日志保留的最大天数(只保留最近多少天的日志)
maxAge: 15
# 只保留最近多少个日志文件,用于控制程序总日志的大小
maxBackups: 10
# 是否使用本地时间,默认使用 UTC 时间
localTime: true
# 是否压缩日志文件,压缩方法 gzip
compress: false

@ -0,0 +1,39 @@
[system]
mode = test #正式prod #测试dev
config_source = configmap
[mysql]
DbHost = ${artist.mysql.host|localhost}
DbPort = ${artist.mysql.port|3306}
DbUser = ${mysql.user}
DbPassWord = ${mysql.password}
DbArtist = ${artist.mysql.db_name}
[redis]
RedisDB = ${artist.redis.db}
RedisAddr = ${artist.redis.addr}
RedisPW = ${redis.password}
RedisDBNAme =
[zap_log]
level= ${artist.zap.level}
filename = ${artist.zap.filename}
max_size = ${zap.max_size}
max_age = ${zap.max_age}
max_backups = ${zap.max_backups}
[jaeger]
jaeger_host = ${jaeger.host}
jaeger_open = ${artist.jaeger_open}
[rabbitmq]
user: ${rabbitmq.user}
password: ${rabbitmq.password}
host: ${rabbitmq.host}
port: ${rabbitmq.port}
vhost_artist= ${artist.rabbitmq.vhost}
vhost_process_data= ${rabbitmq.vhost.process_data}
[baidu]
ak = ${baidu.ocr.ak}
sk = ${baidu.ocr.sk}

@ -0,0 +1,87 @@
dubbo:
metrics:
enable: true # default is true
path: /metrics # default is /metrics
port: 9091 # default is 9090
namespace: dubboArtist # default is dubbo 作为数据上报 metrics 的前缀
registries:
demoZK:
protocol: zookeeper
address: 172.16.100.93:2181
# address: zk-cs:2181
# protocol: nacos
# address: 127.0.0.1:8848
# username: "dyb"
# password: "rootdyb"
# namespace: "4684d3a3-165f-4218-8ab8-f4fa03c8efe0"
# group: GROUP_AERTIST
# data_id: com.fontree.microservices.common.Artist
protocols:
triple: #triple
name: tri
port: 20004
provider:
filter: tracing
services:
ArtistProvider:
interface: com.fontree.microservices.common.Artist
retries: 0
# filter: myServerFilter
# application: "1234"
filter: tps,tracing
tps.limiter: method-service
tps.limit.strategy: fixedWindow
tps.limit.rejected.handler: DefaultValueHandler
tps.limit.interval: 1000
tps.limit.rate: 3000
warmup: 100 #预热时间
ArtistThirdPartyProvider:
interface: com.fontree.microservices.common.ArtistThirdParty
retries: 0
filter: tps,tracing
tps.limiter: method-service
tps.limit.strategy: fixedWindow
tps.limit.rejected.handler: DefaultValueHandler
tps.limit.interval: 1000
tps.limit.rate: 3000
warmup: 100 #预热时间
logger:
zap-config:
level: info # 日志级别
development: false
disableCaller: false
disableStacktrace: false
encoding: "json"
# zap encoder 配置
encoderConfig:
messageKey: "message"
levelKey: "level"
timeKey: "time"
nameKey: "logger"
callerKey: "caller"
stacktraceKey: "stacktrace"
lineEnding: ""
levelEncoder: "capitalColor"
timeEncoder: "iso8601"
durationEncoder: "seconds"
callerEncoder: "short"
nameEncoder: ""
EncodeTime: zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.000"),
EncodeDuration: zapcore.SecondsDurationEncoder,
outputPaths:
- "stderr"
errorOutputPaths:
- "stderr"
lumberjack-config:
# 写日志的文件名称
filename: "runtime/logs/artist_server.log"
# 每个日志文件长度的最大大小,单位是 MiB。默认 100MiB
maxSize: 10
# 日志保留的最大天数(只保留最近多少天的日志)
maxAge: 15
# 只保留最近多少个日志文件,用于控制程序总日志的大小
maxBackups: 10
# 是否使用本地时间,默认使用 UTC 时间
localTime: true
# 是否压缩日志文件,压缩方法 gzip
compress: false

@ -0,0 +1,35 @@
[system]
mode = "dev"
[mysql]
Db = mysql
DbHost = 172.16.100.99
DbPort = 9007
DbUser = artuser
DbPassWord = "C250PflXIWv2SQm8"
DbName = container
[redis]
RedisDb = 1
RedisAddr = 114.218.158.24:9008
RedisPW =
[chain]
IP=127.0.0.1:37101
MnemonicWords=知 睡 迷 纤 纲 耀 镜 婆 渡 考 拔 百
ContractAccount=XC8214684261867838@xuper
ContractName=fp001
[zap_log]
level: "info"
filename: "logs/artistinfo_server.log"
max_size: 200
max_age: 30
max_backups: 7
[bos]
Ak="ALTAKxrqOQHnAN525Tb2GX4Bhe"
Sk="d2ecaa9d75114d3b9f42b99014198306"
BucketName = "dci-file-new"
BosUrl = "https://cdns.fontree.cn"
BosBaseDir = "fonchain-main"

@ -0,0 +1,128 @@
dubbo:
metrics:
enable: true # default is true
path: /metrics # default is /metrics
port: 9091 # default is 9090
namespace: dubboArtist # default is dubbo 作为数据上报 metrics 的前
registries:
demoZK:
protocol: zookeeper
timeout: 120s
# address: 127.0.0.1:2181
# address: 121.229.45.214:9004
# address: 114.218.158.24:2181
address: 172.16.100.93:2181
protocols:
triple: #triple
name: tri
# ip: 121.229.45.214
port: 20050
provider:
services:
ArtistInfoUserProvider:
interface: com.fontree.microservices.common.ArtistInfoUser
retries: 0
ArtistInfoArtworkProvider:
interface: com.fontree.microservices.common.ArtistInfoArtwork
retries: 0
ArtistInfoArtshowProvider:
interface: com.fontree.microservices.common.ArtistInfoArtshow
retries: 0
ArtistInfoContractProvider:
interface: com.fontree.microservices.common.ArtistInfoContract
retries: 0
ArtistInfoStatementProvider:
interface: com.fontree.microservices.common.ArtistInfoStatement
retries: 0
InCircleArticleProvider:
interface: com.fontree.microservices.common.InCircleArticleProvider
retries: 0
CopyrightRegProvider:
interface: com.fontree.microservices.common.CopyrightRegProvider
retries: 0
#ContractProvider:
# interface: com.fontree.microservices.common.Contract
# retries: 0
#ArtWorkProvider:
# interface: com.fontree.microservices.common.ArtWork
# retries: 0
#SupplyProvider:
# interface: com.fontree.microservices.common.Supply
# retries: 0
consumer:
request-timeout: 120s
references:
AccountClientImpl:
protocol: tri
interface: com.fontree.microservices.common.Account
filter: cshutdown,sign,fonDomainFilter,fonValidateFilter
params:
.accessKeyId: "Accountksl"
.secretAccessKey: "BSDY-FDF1-Fontree_account"
ArtistClientImpl:
protocol: tri
interface: com.fontree.microservices.common.Artist
ArtistInfoClientImpl:
protocol: tri
interface: com.fontree.microservices.common.ArtistInfo
ContractClientImpl:
timeout: 15s
protocol: tri
interface: com.fontree.microservices.common.contract
filter: cshutdown,sign
params:
.accessKeyId: "SYD8-Chain-04"
.secretAccessKey: "Al-Chain-FDF112"
ArtworkClientImpl:
protocol: tri
interface: com.fontree.microservices.common.Artwork
ArtworkQueryClientImpl:
protocol: tri
interface: com.fontree.microservices.common.ArtworkQuery
SupplyClientImpl:
protocol: tri
interface: com.fontree.microservices.common.Supply
logger:
zap-config:
level: error # 日志级别
development: false
disableCaller: false
disableStacktrace: false
encoding: "json"
# zap encoder 配置
encoderConfig:
messageKey: "message"
levelKey: "level"
timeKey: "time"
nameKey: "logger"
callerKey: "caller"
stacktraceKey: "stacktrace"
lineEnding: ""
levelEncoder: "capitalColor"
timeEncoder: "iso8601"
durationEncoder: "seconds"
callerEncoder: "short"
nameEncoder: ""
EncodeTime: zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.000"),
EncodeDuration: zapcore.SecondsDurationEncoder,
outputPaths:
- "stderr"
errorOutputPaths:
- "stderr"
lumberjack-config:
# 写日志的文件名称
filename: "logs/artistinfo_server.log"
# 每个日志文件长度的最大大小,单位是 MiB。默认 100MiB
maxSize: 10
# 日志保留的最大天数(只保留最近多少天的日志)
maxAge: 15
# 只保留最近多少个日志文件,用于控制程序总日志的大小
maxBackups: 10
# 是否使用本地时间,默认使用 UTC 时间
localTime: true
# 是否压缩日志文件,压缩方法 gzip
compress: false

@ -1,33 +0,0 @@
module esp8266Server
go 1.21.3
require (
github.com/bytedance/sonic v1.11.6 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gin-gonic/gin v1.10.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/text v0.15.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

@ -1,79 +0,0 @@
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

@ -1,30 +0,0 @@
// Package controller -----------------------------
// @file : led.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2024/5/21 上午10:31
// -------------------------------------------
package controller
import (
"esp8266Server/httpServer/dto"
"esp8266Server/tcp"
"github.com/gin-gonic/gin"
)
type Led struct {
}
func (h *Led) LedControl(c *gin.Context) {
var req dto.LedControlRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
err := tcp.TcpServerIns.SendMsg(req.MchId, req.TcpMsg())
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
c.JSON(200, gin.H{"msg": "success"})
}

@ -1,22 +0,0 @@
// Package httpServer -----------------------------
// @file : httpServer.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2024/5/21 下午1:23
// -------------------------------------------
package httpServer
import (
"esp8266Server/httpServer/controller"
"github.com/gin-gonic/gin"
)
func InitHttpServer() {
r := gin.Default()
LedController := new(controller.Led)
r.POST("/led", LedController.LedControl)
if err := r.Run(":8080"); err != nil {
panic("HTTP server failed to start: " + err.Error())
}
}

@ -1,20 +0,0 @@
// Package esp8266Server -----------------------------
// @file : main.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2024/5/21 上午10:23
// -------------------------------------------
package main
import (
"esp8266Server/httpServer"
"esp8266Server/tcp"
"fmt"
)
func main() {
tcp.InitTcpServer()
fmt.Println("tcp Server started successfully!")
httpServer.InitHttpServer()
//select {}
}

159
go.mod

@ -0,0 +1,159 @@
module github.com/fonchain/fonchain-container
go 1.21.3
require (
dubbo.apache.org/dubbo-go/v3 v3.0.1
github.com/dorlolo/protoc-gen-go-meta v0.0.0-20231010051518-60932b586634
github.com/dubbogo/grpc-go v1.42.9
github.com/dubbogo/triple v1.1.8
github.com/fonchain/utils/objstorage v0.0.0-00010101000000-000000000000
github.com/fonchain/utils/utils v0.0.0-00010101000000-000000000000
github.com/go-redis/redis v6.15.9+incompatible
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0
github.com/golang/protobuf v1.5.2
github.com/jinzhu/copier v0.3.5
github.com/mwitkow/go-proto-validators v0.3.2
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646
github.com/satori/go.uuid v1.2.1-0.20181028125025-b2ce2384e17b
golang.org/x/image v0.0.0-20190802002840-cff245a6509b
google.golang.org/protobuf v1.31.0
gopkg.in/ini.v1 v1.51.0
gorm.io/driver/mysql v1.5.7
gorm.io/gorm v1.25.7
gorm.io/plugin/soft_delete v1.2.1
)
replace (
//github.com/fonchain/electronic-contract => ../electronic-contract
github.com/fonchain/utils/objstorage => ../utils/objstorage
github.com/fonchain/utils/utils => ../utils/utils
github.com/fonchain_enterprise/utils/aes => ../utils/aes
github.com/fonchain_enterprise/utils/baidu => ../utils/baidu
github.com/fonchain_enterprise/utils/chain => ../utils/chain
github.com/fonchain_enterprise/utils/jwt => ../utils/jwt
github.com/fonchain_enterprise/utils/rand => ../utils/rand
)
require (
contrib.go.opencensus.io/exporter/prometheus v0.4.0 // indirect
github.com/RoaringBitmap/roaring v0.7.1 // indirect
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d // indirect
github.com/Workiva/go-datastructures v1.0.52 // indirect
github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5 // indirect
github.com/alibaba/sentinel-golang v1.0.4 // indirect
github.com/aliyun/alibaba-cloud-sdk-go v1.61.18 // indirect
github.com/aliyun/aliyun-oss-go-sdk v2.2.4+incompatible // indirect
github.com/apache/dubbo-getty v1.4.7 // indirect
github.com/apache/dubbo-go-hessian2 v1.11.0 // indirect
github.com/baidubce/bce-sdk-go v0.9.123 // indirect
github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bits-and-blooms/bitset v1.2.0 // indirect
github.com/boombuler/barcode v1.0.1 // indirect
github.com/buger/jsonparser v1.1.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/coreos/go-semver v0.3.0 // indirect
github.com/coreos/go-systemd/v22 v22.3.2 // indirect
github.com/creasty/defaults v1.5.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dubbogo/go-zookeeper v1.0.4-0.20211212162352-f9d2183d89d5 // indirect
github.com/dubbogo/gost v1.11.22 // indirect
github.com/emicklei/go-restful/v3 v3.7.3 // indirect
github.com/fsnotify/fsnotify v1.5.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/ghodss/yaml v1.0.0 // indirect
github.com/go-co-op/gocron v1.9.0 // indirect
github.com/go-errors/errors v1.0.1 // indirect
github.com/go-kit/log v0.1.0 // indirect
github.com/go-logfmt/logfmt v0.5.0 // indirect
github.com/go-logr/logr v0.4.0 // indirect
github.com/go-ole/go-ole v1.2.4 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/go-resty/resty/v2 v2.7.0 // indirect
github.com/go-sql-driver/mysql v1.7.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/mock v1.4.4 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/go-cmp v0.5.6 // indirect
github.com/google/gofuzz v1.1.0 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/gorilla/websocket v1.4.2 // indirect
github.com/grpc-ecosystem/grpc-opentracing v0.0.0-20180507213350-8e809c8a8645 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hashicorp/vault/sdk v0.3.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/k0kubun/pp v3.0.1+incompatible // indirect
github.com/knadh/koanf v1.4.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/magiconair/properties v1.8.5 // indirect
github.com/mattn/go-colorable v0.1.7 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.4.3 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mschoch/smat v0.2.0 // indirect
github.com/nacos-group/nacos-sdk-go v1.1.0 // indirect
github.com/natefinch/lumberjack v2.0.0+incompatible // indirect
github.com/opentracing/opentracing-go v1.2.0 // indirect
github.com/pelletier/go-toml v1.7.0 // indirect
github.com/pierrec/lz4 v2.5.2+incompatible // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/polarismesh/polaris-go v1.0.1 // indirect
github.com/prometheus/client_golang v1.12.1 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.32.1 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/prometheus/statsd_exporter v0.21.0 // indirect
github.com/robfig/cron/v3 v3.0.1 // indirect
github.com/shirou/gopsutil v3.20.11+incompatible // indirect
github.com/shirou/gopsutil/v3 v3.21.6 // indirect
github.com/spaolacci/murmur3 v1.1.0 // indirect
github.com/spf13/afero v1.2.2 // indirect
github.com/spf13/cast v1.3.0 // indirect
github.com/spf13/jwalterweatherman v1.0.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.7.1 // indirect
github.com/stretchr/testify v1.9.0 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
github.com/tklauser/go-sysconf v0.3.6 // indirect
github.com/tklauser/numcpus v0.2.2 // indirect
github.com/toolkits/concurrent v0.0.0-20150624120057-a4371d70e3e3 // indirect
github.com/uber/jaeger-client-go v2.29.1+incompatible // indirect
github.com/uber/jaeger-lib v2.4.1+incompatible // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
github.com/zouyx/agollo/v3 v3.4.5 // indirect
go.etcd.io/etcd/api/v3 v3.5.2 // indirect
go.etcd.io/etcd/client/pkg/v3 v3.5.2 // indirect
go.etcd.io/etcd/client/v3 v3.5.2 // indirect
go.opencensus.io v0.23.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
go.uber.org/zap v1.21.0 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/text v0.15.0 // indirect
golang.org/x/time v0.0.0-20220722155302-e5dcc9cfc0b9 // indirect
google.golang.org/genproto v0.0.0-20211104193956-4c6863e31247 // indirect
google.golang.org/grpc v1.44.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
k8s.io/apimachinery v0.22.4 // indirect
k8s.io/klog/v2 v2.9.0 // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.1.2 // indirect
)

1451
go.sum

File diff suppressed because it is too large Load Diff

@ -0,0 +1,11 @@
syntax = "proto3";
package container;
option go_package = "./;container";
import public "google/protobuf/timestamp.proto";
import "google/protobuf/empty.proto";
import "github.com/mwitkow/go-proto-validators/validator.proto";
service Container{
}

@ -0,0 +1,77 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.31.0
// protoc v4.22.0--rc2
// source: pb/container.proto
package container
import (
_ "github.com/mwitkow/go-proto-validators"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
_ "google.golang.org/protobuf/types/known/emptypb"
timestamppb "google.golang.org/protobuf/types/known/timestamppb"
reflect "reflect"
)
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)
)
// Symbols defined in public import of google/protobuf/timestamp.proto.
type Timestamp = timestamppb.Timestamp
var File_pb_container_proto protoreflect.FileDescriptor
var file_pb_container_proto_rawDesc = []byte{
0x0a, 0x12, 0x70, 0x62, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x2e, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x12, 0x09, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x1a,
0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66,
0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x1a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75,
0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x36, 0x67,
0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x6d, 0x77, 0x69, 0x74, 0x6b, 0x6f,
0x77, 0x2f, 0x67, 0x6f, 0x2d, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2d, 0x76, 0x61, 0x6c, 0x69, 0x64,
0x61, 0x74, 0x6f, 0x72, 0x73, 0x2f, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x32, 0x0b, 0x0a, 0x09, 0x43, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e,
0x65, 0x72, 0x42, 0x0e, 0x5a, 0x0c, 0x2e, 0x2f, 0x3b, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e,
0x65, 0x72, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var file_pb_container_proto_goTypes = []interface{}{}
var file_pb_container_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_pb_container_proto_init() }
func file_pb_container_proto_init() {
if File_pb_container_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_pb_container_proto_rawDesc,
NumEnums: 0,
NumMessages: 0,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_pb_container_proto_goTypes,
DependencyIndexes: file_pb_container_proto_depIdxs,
}.Build()
File_pb_container_proto = out.File
file_pb_container_proto_rawDesc = nil
file_pb_container_proto_goTypes = nil
file_pb_container_proto_depIdxs = nil
}

@ -0,0 +1,18 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: pb/container.proto
package container
import (
fmt "fmt"
math "math"
proto "github.com/golang/protobuf/proto"
_ "github.com/mwitkow/go-proto-validators"
_ "google.golang.org/protobuf/types/known/emptypb"
_ "google.golang.org/protobuf/types/known/timestamppb"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

@ -0,0 +1,93 @@
// Code generated by protoc-gen-go-triple. DO NOT EDIT.
// versions:
// - protoc-gen-go-triple v1.0.8
// - protoc v4.22.0--rc2
// source: pb/container.proto
package container
import (
protocol "dubbo.apache.org/dubbo-go/v3/protocol"
grpc_go "github.com/dubbogo/grpc-go"
triple "github.com/dubbogo/triple/pkg/triple"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc_go.SupportPackageIsVersion7
// ContainerClient is the client API for Container service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type ContainerClient interface {
}
type containerClient struct {
cc *triple.TripleConn
}
type ContainerClientImpl struct {
}
func (c *ContainerClientImpl) GetDubboStub(cc *triple.TripleConn) ContainerClient {
return NewContainerClient(cc)
}
func (c *ContainerClientImpl) XXX_InterfaceName() string {
return "container.Container"
}
func NewContainerClient(cc *triple.TripleConn) ContainerClient {
return &containerClient{cc}
}
// ContainerServer is the server API for Container service.
// All implementations must embed UnimplementedContainerServer
// for forward compatibility
type ContainerServer interface {
mustEmbedUnimplementedContainerServer()
}
// UnimplementedContainerServer must be embedded to have forward compatible implementations.
type UnimplementedContainerServer struct {
proxyImpl protocol.Invoker
}
func (s *UnimplementedContainerServer) XXX_SetProxyImpl(impl protocol.Invoker) {
s.proxyImpl = impl
}
func (s *UnimplementedContainerServer) XXX_GetProxyImpl() protocol.Invoker {
return s.proxyImpl
}
func (s *UnimplementedContainerServer) XXX_ServiceDesc() *grpc_go.ServiceDesc {
return &Container_ServiceDesc
}
func (s *UnimplementedContainerServer) XXX_InterfaceName() string {
return "container.Container"
}
func (UnimplementedContainerServer) mustEmbedUnimplementedContainerServer() {}
// UnsafeContainerServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to ContainerServer will
// result in compilation errors.
type UnsafeContainerServer interface {
mustEmbedUnimplementedContainerServer()
}
func RegisterContainerServer(s grpc_go.ServiceRegistrar, srv ContainerServer) {
s.RegisterService(&Container_ServiceDesc, srv)
}
// Container_ServiceDesc is the grpc_go.ServiceDesc for Container service.
// It's only intended for direct use with grpc_go.RegisterService,
// and not to be introspected or modified (even as a copy)
var Container_ServiceDesc = grpc_go.ServiceDesc{
ServiceName: "container.Container",
HandlerType: (*ContainerServer)(nil),
Methods: []grpc_go.MethodDesc{},
Streams: []grpc_go.StreamDesc{},
Metadata: "pb/container.proto",
}

@ -0,0 +1,8 @@
syntax = "proto3";
package meta;
option go_package = "github.com/dorlolo/protoc-gen-go-meta/meta;meta";
import "google/protobuf/descriptor.proto";
extend google.protobuf.EnumValueOptions {
optional string enum_value = 51234;
}

@ -0,0 +1,80 @@
// Copyright 2016 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
// Protocol Buffers extensions for defining auto-generateable validators for messages.
// TODO(mwitkow): Add example.
syntax = "proto2";
package validator;
import "google/protobuf/descriptor.proto";
option go_package = "github.com/mwitkow/go-proto-validators;validator";
// TODO(mwitkow): Email protobuf-global-extension-registry@google.com to get an extension ID.
extend google.protobuf.FieldOptions {
optional FieldValidator field = 65020;
}
extend google.protobuf.OneofOptions {
optional OneofValidator oneof = 65021;
}
message FieldValidator {
// Uses a Golang RE2-syntax regex to match the field contents.
optional string regex = 1;
// Field value of integer strictly greater than this value.
optional int64 int_gt = 2;
// Field value of integer strictly smaller than this value.
optional int64 int_lt = 3;
// Used for nested message types, requires that the message type exists.
optional bool msg_exists = 4;
// Human error specifies a user-customizable error that is visible to the user.
optional string human_error = 5;
// Field value of double strictly greater than this value.
// Note that this value can only take on a valid floating point
// value. Use together with float_epsilon if you need something more specific.
optional double float_gt = 6;
// Field value of double strictly smaller than this value.
// Note that this value can only take on a valid floating point
// value. Use together with float_epsilon if you need something more specific.
optional double float_lt = 7;
// Field value of double describing the epsilon within which
// any comparison should be considered to be true. For example,
// when using float_gt = 0.35, using a float_epsilon of 0.05
// would mean that any value above 0.30 is acceptable. It can be
// thought of as a {float_value_condition} +- {float_epsilon}.
// If unset, no correction for floating point inaccuracies in
// comparisons will be attempted.
optional double float_epsilon = 8;
// Floating-point value compared to which the field content should be greater or equal.
optional double float_gte = 9;
// Floating-point value compared to which the field content should be smaller or equal.
optional double float_lte = 10;
// Used for string fields, requires the string to be not empty (i.e different from "").
optional bool string_not_empty = 11;
// Repeated field with at least this number of elements.
optional int64 repeated_count_min = 12;
// Repeated field with at most this number of elements.
optional int64 repeated_count_max = 13;
// Field value of length greater than this value.
optional int64 length_gt = 14;
// Field value of length smaller than this value.
optional int64 length_lt = 15;
// Field value of length strictly equal to this value.
optional int64 length_eq = 16;
// Requires that the value is in the enum.
optional bool is_in_enum = 17;
// Ensures that a string value is in UUID format.
// uuid_ver specifies the valid UUID versions. Valid values are: 0-5.
// If uuid_ver is 0 all UUID versions are accepted.
optional int32 uuid_ver = 18;
}
message OneofValidator {
// Require that one of the oneof fields is set.
optional bool required = 1;
}

51
pkg/cache/redis.go vendored

@ -0,0 +1,51 @@
package cache
import (
"fmt"
"strconv"
"github.com/go-redis/redis"
"gopkg.in/ini.v1"
)
// RedisClient Redis缓存客户端单例
var (
RedisClient *redis.Client
RedisDB int
RedisAddr string
RedisPw string
//RedisDbName string
)
// InitRedis 在中间件中初始化redis链接 防止循环导包,所以放在这里
func InitRedis(confPath string) {
//从本地读取环境变量
file, err := ini.Load(confPath)
if err != nil {
panic(err)
}
LoadRedisData(file)
connRedis()
}
// connRedis 在中间件中初始化redis链接
func connRedis() {
RedisClient = redis.NewClient(&redis.Options{
Addr: RedisAddr,
Password: RedisPw,
DB: RedisDB,
})
_, err := RedisClient.Ping().Result()
if err != nil {
fmt.Println("connRedis err", err)
panic(err)
}
}
func LoadRedisData(file *ini.File) {
dbStr := file.Section("redis").Key("RedisDb").String()
RedisDB, _ = strconv.Atoi(dbStr)
RedisAddr = file.Section("redis").Key("RedisAddr").String()
RedisPw = file.Section("redis").Key("RedisPW").String()
//RedisDbName = file.Section("redis").Key("RedisDbName").String()
}

@ -0,0 +1,50 @@
// Package cache -----------------------------
// @file : redis_test.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2023/11/28 10:27
// -------------------------------------------
package cache
import (
"encoding/json"
"fmt"
"github.com/go-redis/redis"
"testing"
)
// RedisDB = 2
// RedisAddr = svc-fontree-redis-service:6379
// RedisPW = "fonchain_opv:kP6tW4tS3qB2dW4aE6uI5cX2"
func Test_connRedis(t *testing.T) {
RedisClient = redis.NewClient(&redis.Options{
Addr: "https://svc-fontree-redis-service:6379",
Password: "fonchain_opv:kP6tW4tS3qB2dW4aE6uI5cX2",
DB: 2,
})
_, err := RedisClient.Ping().Result()
if err != nil {
t.Error(err)
return
}
var cacheBytes []byte
var cacheData = make(map[string]map[string]*artistInfoArtwork.TempSaveReviewStatusData)
val := RedisClient.Get("artistinfo:review_artwok_base")
if val.Err() == nil {
err2 := val.Scan(&cacheBytes)
if err2 != nil {
fmt.Println("redis scan error", err2.Error())
return
}
err2 = json.Unmarshal(cacheBytes, &cacheData)
if err2 != nil {
fmt.Println("cache bytes unmarshall error", err2)
return
}
}
if _, ok := cacheData["30e7e34e-88ce-43ab-812f-f12095336888"]; ok {
fmt.Println("have cache:true")
} else {
fmt.Println("have cache:false")
}
}

@ -0,0 +1,40 @@
// Package config -----------------------------
// @file : bos.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2023/10/19 10:50
// -------------------------------------------
package config
import (
"fmt"
"gopkg.in/ini.v1"
"log"
)
var Bos = bosConfig{}
type bosConfig struct {
AK string `ini:"Ak"`
SK string `ini:"Sk"`
BucketName string `ini:"BucketName"`
BaseDir string `ini:"BosBaseDir"`
Url string `ini:"BosUrl"`
}
func (b *bosConfig) SectionName() string {
return "bos"
}
func (b *bosConfig) LoadConfig(file *ini.File) {
section := file.Section(b.SectionName())
err := section.MapTo(b)
if err != nil {
log.Println(err.Error())
}
fmt.Println("bos config:")
fmt.Println("\tBosSK:", b.AK)
fmt.Println("\tBosSK:", b.SK)
fmt.Println("\tBosBucketName:", b.BucketName)
fmt.Println("\tBosBaseDir:", b.BaseDir)
fmt.Println("\tBosUrl:", b.Url)
}

@ -0,0 +1,27 @@
// Package config -----------------------------
// @file : config.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2023/8/22 14:02
// -------------------------------------------
package config
import (
"gopkg.in/ini.v1"
)
var (
Mode string
)
func LoadConfig(confPath string) error {
file, err := ini.Load(confPath)
if err != nil {
return err
}
Mode = file.Section("system").Key("mode").String()
Bos.LoadConfig(file)
Zap.LoadConfig(file)
return nil
}

@ -0,0 +1,33 @@
// Package config -----------------------------
// @file : zapLog.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2024/7/2 上午11:14
// -------------------------------------------
package config
import (
"gopkg.in/ini.v1"
"log"
)
var Zap = zapConfig{}
type zapConfig struct {
Level string `ini:"level"`
Filename string `ini:"filename"`
MaxSize string `ini:"max_size"`
MaxAge string `ini:"max_age"`
MaxBackups string `ini:"max_backups"`
}
func (b *zapConfig) SectionName() string {
return "zap_log"
}
func (b *zapConfig) LoadConfig(file *ini.File) {
section := file.Section(b.SectionName())
err := section.MapTo(b)
if err != nil {
log.Println(err.Error())
}
}

@ -0,0 +1,131 @@
package model
import (
"fmt"
"github.com/fonchain/fonchain-container/pkg/config"
"gopkg.in/ini.v1"
"os"
"strings"
"time"
"github.com/fonchain/fonchain-container/cmd/model"
"github.com/fonchain/fonchain-container/pkg/m"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
)
var DB *gorm.DB
var (
Db string
DbHost string
DbPort string
DbUser string
DbPassWord string
DbLogName string
)
func Init(confPath string) {
//从本地读取环境变量
file, err := ini.Load(confPath)
if err != nil {
fmt.Println(m.ERROR_SERVER, err)
}
//加载数据库配置
LoadMysqlData(file)
//MySQL数据库
path := strings.Join([]string{DbUser, ":", DbPassWord, "@tcp(", DbHost, ":", DbPort, ")/", DbLogName, "?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai"}, "")
//连接数据库
Database(path)
//迁移表 如果需要就打开使用
migration()
// 生成视图 ,如果更新报错需要手动删除视图后再执行程序
if err = generateModelView(); err != nil {
fmt.Println("创建或更新视图失败,错误内容:", err.Error())
os.Exit(1)
}
}
func LoadMysqlData(file *ini.File) {
Db = file.Section("mysql").Key("Db").String()
DbHost = file.Section("mysql").Key("DbHost").String()
DbPort = file.Section("mysql").Key("DbPort").String()
DbUser = file.Section("mysql").Key("DbUser").String()
DbPassWord = file.Section("mysql").Key("DbPassWord").String()
DbLogName = file.Section("mysql").Key("DbName").String()
fmt.Println("数据库配置=====================================================")
fmt.Println("\tDb:", Db)
fmt.Println("\tDbHost:", DbHost)
fmt.Println("\tDbPort:", DbPort)
fmt.Println("\tDbUser:", DbUser)
fmt.Println("\tDbPassWord:", DbPassWord)
fmt.Println("\tDbLogName:", DbLogName)
}
func Database(conn string) {
var ormLogger logger.Interface
if config.Zap.Level == "debug" {
ormLogger = logger.Default.LogMode(logger.Info)
} else {
ormLogger = logger.Default
}
db, err := gorm.Open(mysql.New(mysql.Config{
DSN: conn, // DSN data source name
DefaultStringSize: 256, // string 类型字段的默认长度
DisableDatetimePrecision: true, // 禁用 datetime 精度MySQL 5.6 之前的数据库不支持
DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
DontSupportRenameColumn: true, // 用 `change` 重命名列MySQL 8 之前的数据库和 MariaDB 不支持重命名列
SkipInitializeWithVersion: false, // 根据版本自动配置
}), &gorm.Config{
Logger: ormLogger,
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
},
DisableForeignKeyConstraintWhenMigrating: true, //表结构迁移时禁用外键约束(不会添加外键关联)
})
sqlDB, _ := db.DB()
sqlDB.SetMaxIdleConns(20) //设置连接池,空闲
sqlDB.SetMaxOpenConns(100) //打开
sqlDB.SetConnMaxLifetime(time.Second * 30)
DB = db
if err != nil {
panic(err)
}
}
func migration() {
//自迁移模式
err := DB.AutoMigrate(
&model.Container{}, //货柜
&model.ContainerBox{}, //货柜格子/孔洞
&model.Tag{}, //标签
&model.Device{}, //设备
&model.DevicePin{}, //设备引脚
&model.BoxRelPin{}, //各自与设备引脚的关联
&model.OperationRecord{}, //操作记录
)
if err != nil {
fmt.Println("register table fail")
fmt.Println(err.Error())
os.Exit(0)
}
fmt.Println("register table success")
}
// 创建视图
func generateModelView(functions ...func(db *gorm.DB) error) (err error) {
if functions == nil {
return
}
for _, viewFunc := range functions {
err = viewFunc(DB)
if err != nil {
return err
}
}
return nil
}

@ -0,0 +1,19 @@
// Package model -----------------------------
// @file : videoDto.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2023/2/27 11:54
// -------------------------------------------
package model
import "gorm.io/gorm"
func Pagination[T int | int32 | int64](page T, pageSize T) func(db *gorm.DB) *gorm.DB {
if page == 0 || pageSize == 0 {
page = 1
pageSize = 15
}
return func(db *gorm.DB) *gorm.DB {
return db.Limit(int(pageSize)).Offset(int((page - 1) * pageSize))
}
}

@ -0,0 +1,23 @@
// Package m -----------------------------
// @file : system.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2024/7/1 下午1:43
// -------------------------------------------
package m
const (
SERVER_CONFIG = "../conf/conf.ini"
)
const (
SUCCESS = "success"
FAILED = "failed"
)
const (
ERROR_SERVER = "服务器错误"
ERROR_STRUCT = "结构体错误"
ERROR_UID = "uid创建错误"
ERROR_DELETE = "删除错误"
ERROR_UPDATE = "更新异常"
)

@ -0,0 +1,16 @@
package service
var (
// GrpcContainerImpl = new(artist.ArtistClientImpl)
)
func init() {
//config.SetConsumerService(GrpcArtistImpl)
//if os.Args[len(os.Args)-1] == "unit-test" {
// _ = os.Setenv(constant.ConfigFileEnvKey, "../../conf/dubbogo.yaml")
//}
//fmt.Println(os.Getenv(constant.ConfigFileEnvKey))
//if err := config.Load(); err != nil {
// panic(err)
//}
}

@ -0,0 +1,41 @@
// Package ticker -----------------------------
// @file : ticker.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2023/5/6 8:18
// -------------------------------------------
package ticker
import (
"fmt"
"time"
)
type TaskInter interface {
Run() error
TaskName() string
}
// 定时器模块
const timerSpace = 10 //定时任务执行间隔,单位:分钟
func SimpleRunTimerTask(tasks ...TaskInter) {
doTasks(tasks...)
var ticker = time.NewTicker(time.Minute * timerSpace)
for {
select {
case <-ticker.C:
fmt.Println("run timer task")
doTasks(tasks...)
}
}
}
func doTasks(tasks ...TaskInter) {
for _, t := range tasks {
if err := t.Run(); err != nil {
fmt.Printf("执行定时任务 [ %s ] 失败: %s\n", t.TaskName(), err.Error())
} else {
fmt.Printf("执行定时任务 [ %s ] 成功:\n", t.TaskName())
}
}
}

@ -0,0 +1,44 @@
// Package util -----------------------------
// @file : copierOptions.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2023/8/18 12:00
// -------------------------------------------
package util
import (
"errors"
"github.com/fonchain/fonchain-container/pkg/util/stime"
"github.com/jinzhu/copier"
"time"
)
var CopierProtoOptions = copier.Option{
IgnoreEmpty: true,
DeepCopy: true,
Converters: []copier.TypeConverter{
{
SrcType: time.Time{},
DstType: copier.String,
Fn: func(src interface{}) (interface{}, error) {
s, ok := src.(time.Time)
if !ok {
return nil, errors.New("src type :time.Time not matching")
}
return s.Format(stime.Format_Normal_YMDhms), nil
},
},
{
SrcType: copier.String,
DstType: time.Time{},
Fn: func(src interface{}) (interface{}, error) {
s, ok := src.(string)
if !ok {
return nil, errors.New("src type :time.Time not matching")
}
tt, err := stime.StringToTimeWithFormat(s, stime.Format_Normal_YMDhms)
return *tt, err
},
},
},
}

@ -0,0 +1,41 @@
// Package utils -----------------------------
// @file : excelHelper.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2022/6/9 13:41
// -------------------------------------------
package excel
import (
"fmt"
"strconv"
)
// 行列坐标值转换为excel的坐标。注意row和columnCount的初始值都是1
func GetCellIndex(row int, columnCount int) string {
var column = getColumnIndex(columnCount)
return fmt.Sprintf("%s%d", column, row)
}
// 获取excel的列索引
var columnIndices = []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
func getColumnIndex(num int) string {
num--
var column = columnIndices[num%26]
for num = num / 26; num > 0; num = num / 26 {
column = columnIndices[(num-1)%26] + column
num--
}
return column
}
func Int[T int | uint | uint8 | uint32 | uint64 | int32 | int64](value string) T {
v, _ := strconv.Atoi(value)
return T(v)
}
func Float[T float64 | float32](value string) T {
v, _ := strconv.ParseFloat(value, 64)
return T(v)
}

@ -0,0 +1,36 @@
package util
import (
"fmt"
"os"
)
func CreateArtistInfo(id int64) {
if _, err := os.Stat("static/artist/" + fmt.Sprintf("%d", id) + "/"); err != nil {
if !os.IsExist(err) {
os.MkdirAll("static/artist/"+fmt.Sprintf("%d", id)+"/", os.ModePerm)
}
}
if _, err := os.Stat("static/artist/" + fmt.Sprintf("%d", id) + "/info/"); err != nil {
if !os.IsExist(err) {
os.MkdirAll("static/artist/"+fmt.Sprintf("%d", id)+"/info", os.ModePerm)
}
}
}
func CreateArtworkInfo(id int64) {
if _, err := os.Stat("static/artwork/" + fmt.Sprintf("%d", id) + "/"); err != nil {
if !os.IsExist(err) {
os.MkdirAll("static/artwork/"+fmt.Sprintf("%d", id)+"/", os.ModePerm)
}
}
}
func SaveFileFromBytes(filePath string, raw []byte) error {
err := os.WriteFile(filePath, raw, 0644)
if err != nil {
return err
}
return nil
}

@ -0,0 +1,62 @@
package idcard
import (
"fmt"
"github.com/fonchain/fonchain-container/pkg/util/stime"
"strconv"
)
const DEF_IDCARD_LEN = 18
func GetNativePlace(idNum string) string {
if idNum == "" {
return ""
}
var area = map[int]string{
11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古",
21: "辽宁", 22: "吉林", 23: "黑龙江", 31: "上海", 32: "江苏",
33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北",
43: "湖南", 44: "广东", 45: "广西",
46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏", 61: "陕西",
62: "甘肃", 63: "青海", 64: "宁夏",
65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外",
}
var provinceName = ""
var ok bool
var provinceNo, _ = strconv.Atoi(idNum[0:2])
if provinceNo == 0 {
return ""
}
if provinceName, ok = area[provinceNo]; ok {
return provinceName
} else {
return ""
}
}
func GetAge(idNum string) int {
if len(idNum) < 18 {
return 0
}
birthdayStr := idNum[6:14]
fmt.Println("--------===--- idNum", idNum, "birthdayStr", birthdayStr)
birthday, _ := stime.StringToTimeWithFormat(birthdayStr, stime.Format_NoSpacer_YMD)
if birthday == nil {
return 0
}
return stime.GetAge(*birthday)
}
func Validate(idCard string) bool {
idLen := len(idCard)
if idLen != DEF_IDCARD_LEN { // lenght check failed
return false
}
weight := []int{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}
validate := []byte{'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'}
sum := 0
for i := 0; i < len(weight); i++ {
sum += weight[i] * int(byte(idCard[i])-'0')
}
m := sum % 11
return validate[m] == idCard[idLen-1]
}

@ -0,0 +1,13 @@
package idcard
import (
"testing"
)
func TestGetNativePlace(t *testing.T) {
t.Log(GetNativePlace("32058119910306341X"))
}
func TestGetAge(t *testing.T) {
t.Log(GetAge("32058119910306341X"))
}

@ -0,0 +1,15 @@
/*
* @FileName: if.go
* @Author: JJXu
* @CreateTime: 2022/3/31 10:34
* @Description:
*/
package util
func If[T int | int64 | int32 | string | float32 | float64 | bool](condition bool, trueVal, falseVal T) T {
if condition {
return trueVal
}
return falseVal
}

@ -0,0 +1,45 @@
// Package util -----------------------------
// @file : list.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2023/6/1 16:40
// -------------------------------------------
package util
import "strings"
func UniqueBaseTypeList[T comparable](list []T) []T {
uniqueList := make([]T, 0, len(list))
seen := make(map[T]bool)
for _, item := range list {
if !seen[item] {
seen[item] = true
uniqueList = append(uniqueList, item)
}
}
return uniqueList
}
// IsValueInList 值是否在列表中
// value:查询的值
// list: 列表
// disableStrictCase: 禁用严格大小写检查。默认是严格大小写
func IsValueInList(value string, list []string, disableStrictCase ...bool) bool {
var disStrictCase bool
if disableStrictCase != nil {
disStrictCase = disableStrictCase[0]
}
for _, v := range list {
var listValue string
if disStrictCase {
listValue = strings.ToLower(v)
value = strings.ToLower(v)
} else {
listValue = v
}
if listValue == value {
return true
}
}
return false
}

@ -0,0 +1,37 @@
// Package util -----------------------------
// @file : list_test.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2023/6/1 16:48
// -------------------------------------------
package util
import (
"reflect"
"testing"
)
func Test_uniqueBaseTypeList(t *testing.T) {
type args[T comparable] struct {
list []T
}
type testCase[T comparable] struct {
name string
args args[T]
want []T
}
tests := []testCase[int]{
{
name: "test1",
args: args[int]{list: []int{1, 1, 2, 3, 4, 2}},
want: []int{1, 2, 3, 4},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := UniqueBaseTypeList(tt.args.list); !reflect.DeepEqual(got, tt.want) {
t.Errorf("uniqueBaseTypeList() = %v, want %v", got, tt.want)
}
})
}
}

@ -0,0 +1,129 @@
package util
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"io/ioutil"
"log"
"os"
"github.com/fonchain/utils/utils"
"github.com/golang/freetype"
"github.com/nfnt/resize"
"golang.org/x/image/font"
)
func CreateQrCode(invitedCode, userName string) error {
QrCodePath, err := utils.GenQRCode("https://artist.fontree.cn/login?invitedCode=" + invitedCode)
if err != nil {
return err
}
tmp, err := os.Open(QrCodePath)
if err != nil {
return err
}
defer tmp.Close()
src, err := os.Open("./qrcodebg.png")
if err != nil {
log.Println(err)
return err
}
defer src.Close()
img, err := png.Decode(src)
if err != nil {
log.Println(err)
return err
}
outimage, _ := addLabel(img, userName+"邀请您注册画家宝用户", 210, 300, color.RGBA{255, 255, 255, 255}, 55, "font1716.ttf")
outimage, _ = addLabel(outimage, "(使用此二维码后,"+userName+"将成为你的邀请人)", 210, 400, color.RGBA{255, 255, 255, 255}, 38, "font1716.ttf")
outimage, _ = addLabel(outimage, "邀请码:"+invitedCode, 260, 1340, color.RGBA{69, 137, 239, 255}, 70, "font1716.ttf")
QrCode2Path := "static/qrcode/" + invitedCode + "-2.png"
f, err := os.Create(QrCode2Path)
if err != nil {
log.Println(err)
return err
}
defer f.Close()
newImg := image.NewNRGBA(image.Rect(0, 0, 1125, 2436))
// fe, err := os.Open("./" + artistPhoto.SmallPic + "_small.jpg")
qrImg, err := png.Decode(tmp)
if err != nil {
fmt.Println(err.Error())
return err
}
qrImg = resize.Resize(uint(700), uint(700), qrImg, resize.Lanczos3)
draw.Draw(newImg, newImg.Bounds(), outimage, outimage.Bounds().Min.Sub(image.Pt(0, 0)), draw.Over)
draw.Draw(newImg, newImg.Bounds(), qrImg, qrImg.Bounds().Min.Sub(image.Pt(210, 570)), draw.Over)
err = png.Encode(f, newImg)
if err != nil {
return err
}
tmp.Close()
tmps, err := os.OpenFile(QrCodePath, os.O_RDWR|os.O_CREATE, 0777)
if err != nil {
return err
}
defer tmps.Close()
_, err = UploadToBos(tmps, fmt.Sprintf("artistmgmt/static/qrcode/%v.png", invitedCode))
if err != nil {
return err
}
// fmt.Println(urlss)
tmp2, err := os.Open(QrCode2Path)
if err != nil {
return err
}
defer tmp2.Close()
str, err := UploadToBos(tmp2, fmt.Sprintf("artistmgmt/static/qrcode/%v-2.png", invitedCode))
if err != nil {
return err
}
fmt.Println(str, "===============")
return nil
}
func addLabel(img image.Image, label string, x, y int, fontColor color.Color, size float64, fontPath string) (image.Image, error) {
bound := img.Bounds()
// 创建一个新的图片
rgba := image.NewRGBA(image.Rect(0, 0, bound.Dx(), bound.Dy()))
// 读取字体
fontBytes, err := ioutil.ReadFile(fontPath)
if err != nil {
return rgba, err
}
myFont, err := freetype.ParseFont(fontBytes)
if err != nil {
return rgba, err
}
draw.Draw(rgba, rgba.Bounds(), img, bound.Min, draw.Src)
c := freetype.NewContext()
c.SetDPI(72)
c.SetFont(myFont)
c.SetFontSize(size)
c.SetClip(rgba.Bounds())
c.SetDst(rgba)
uni := image.NewUniform(fontColor)
c.SetSrc(uni)
c.SetHinting(font.HintingNone)
// 在指定的位置显示
pt := freetype.Pt(x, y+int(c.PointToFixed(size)>>6))
if _, err := c.DrawString(label, pt); err != nil {
return rgba, err
}
return rgba, nil
}

@ -0,0 +1,90 @@
// Package stime -----------------------------
// @file : common.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2022/10/21 00:19:04
// -------------------------------------------
package stime
import (
"time"
)
var Loc loc
type loc time.Location
func (l loc) Shanghai() *time.Location {
var shanghai, err = time.LoadLocation("Asia/Shanghai")
if err != nil {
shanghai = time.FixedZone("CST", 8*3600)
}
return shanghai
}
const (
//常规时间格式(日期带横杠)
Format_Normal_YMDhms = "2006-01-02 15:04:05"
Format_Normal_YMD = "2006-01-02"
Format_Normal_hms = "15:04:05"
Format_Normal_hm = "15:04"
Format_Normal_YM = "2006-01"
//带斜杠的时间格式
Format_Slash_YMDhms = "2006/01/02 15:04:05"
Format_Slash_YMD = "2006/01/02"
//无间隔符
Format_NoSpacer_YMDhms = "20060102150405"
Format_NoSpacer_YMD = "20060102"
Format_ChinaChar_YMD = "2006年01月02日"
Format_ChinaChar_YMDhm = "2006年01月02日 15时04分"
Format_DB_YMDhms = "2006-01-02T15:04:05+08:00"
)
var MonthStrMap = map[string]string{
"January": "01",
"February": "02",
"March": "03",
"April": "04",
"May": "05",
"June": "06",
"July": "07",
"August": "08",
"September": "09",
"October": "10",
"November": "11",
"December": "12",
}
var MonthIntMap = map[string]int{
"January": 1,
"February": 2,
"March": 3,
"April": 4,
"May": 5,
"June": 6,
"July": 7,
"August": 8,
"September": 9,
"October": 10,
"November": 11,
"December": 12,
}
var WeekIntMap = map[string]int{
"Monday": 1,
"Tuesday": 2,
"Wednesday": 3,
"Thursday": 4,
"Friday": 5,
"Saturday": 6,
"Sunday": 7,
}
var WeekStrMap = map[string]string{
"Monday": "一",
"Tuesday": "二",
"Wednesday": "三",
"Thursday": "四",
"Friday": "五",
"Saturday": "六",
"Sunday": "日",
}

@ -0,0 +1,157 @@
/*
* @FileName: getTime.go
* @Author: JJXu
* @CreateTime: 2022/3/1 6:35
* @Description:
*/
package stime
import (
"fmt"
"time"
)
func StrNowDate() string {
return TimeToString(time.Now(), Format_Normal_YMD)
}
func StrNowYearMonth() string {
return TimeToString(time.Now(), Format_Normal_YM)
}
// ThisMorming 今天凌晨
func ThisMorming(format string) (strTime string) {
thisTime := time.Now()
year := thisTime.Year()
month := MonthStrMap[thisTime.Month().String()]
day := fmt.Sprintf("%02d", thisTime.Day())
strTime = fmt.Sprintf("%v-%v-%v 00:00:00", year, month, day)
if format != Format_Normal_YMDhms {
t1, _ := time.ParseInLocation(Format_Normal_YMDhms, strTime, Loc.Shanghai())
strTime = t1.Format(format)
}
return strTime
}
// ThisMorningUnix 获取当日凌晨的时间戳
func ThisMorningToUnix() int64 {
thist := time.Now()
zero_tm := time.Date(thist.Year(), thist.Month(), thist.Day(), 0, 0, 0, 0, thist.Location()).Unix()
return zero_tm
}
// TomorrowMorning 第二天凌晨
func TomorrowMorning(baseTime time.Time) *time.Time {
year := baseTime.Year()
month := MonthStrMap[baseTime.Month().String()]
day := fmt.Sprintf("%02d", baseTime.Day()+1)
strTime := fmt.Sprintf("%v-%v-%v 00:00:00", year, month, day)
res, _ := StringToTime(strTime)
return res
}
// ThisTimeUnix 获取当前时间的时间戳
func CurrentimeToUnix() int64 {
return time.Now().Unix()
}
// Currentime 获取当前时间
func Currentime(format string) (strTime string) {
strTime = time.Now().Format(format)
return
}
// HoursAgo 若干小时之前的时间
func HoursAgo(hours time.Duration, format string) (lastTimeStr string) {
lastStamp := time.Now().Unix() - int64((time.Hour * hours).Seconds())
lastTime := time.Unix(lastStamp, 0).In(Loc.Shanghai())
lastTimeStr = lastTime.Format(format)
return
}
// TimeToString 时间转字符串
func TimeToString(t time.Time, format string) string {
return t.Format(format)
}
// 计算指定月份的天数
func YearMonthToDayNumber(year int, month int) int {
// 有31天的月份
day31 := map[int]bool{
1: true,
3: true,
5: true,
7: true,
8: true,
10: true,
12: true,
}
if day31[month] == true {
return 31
}
// 有30天的月份
day30 := map[int]bool{
4: true,
6: true,
9: true,
11: true,
}
if day30[month] == true {
return 30
}
// 计算是平年还是闰年
if (year%4 == 0 && year%100 != 0) || year%400 == 0 {
// 得出2月的天数
return 29
}
// 得出2月的天数
return 28
}
// 求时间差返回一个数字该数字单位由传过来的unit决定。若unit为60则单位是分钟。
func GetDiffTime(start_time string, end_time string, unit int64) int64 {
// 转成时间戳
if len(start_time) == 10 {
start_time = fmt.Sprintf("%v 00:00:00", start_time)
}
if len(end_time) == 10 {
end_time = fmt.Sprintf("%v 00:00:00", end_time)
}
startUnix, _ := time.ParseInLocation("2006-01-02 15:04:05", start_time, Loc.Shanghai())
endUnix, _ := time.ParseInLocation("2006-01-02 15:04:05", end_time, Loc.Shanghai())
startTime := startUnix.Unix()
endTime := endUnix.Unix()
// 求相差天数
date := (endTime - startTime) / unit
return date
}
func TimeSince(pastTime string, format string) string {
t, err := time.Parse(format, pastTime)
if err != nil {
return ""
}
diff := time.Since(t)
if diff.Minutes() < 15 {
return "刚刚"
} else if diff.Minutes() >= 15 && diff.Minutes() < 30 {
return "15分钟前"
} else if diff.Minutes() >= 30 && diff.Minutes() < 60 {
return "半小时前"
} else if diff.Hours() >= 1 && diff.Hours() < 24 {
return fmt.Sprintf("%d小时前", int(diff.Hours()))
} else if diff.Hours() >= 24 && diff.Hours() < 24*15 {
return fmt.Sprintf("%d天前", int(diff.Hours()/24))
} else if diff.Hours() < 24*30 {
return "半月前"
} else if diff.Hours() < 24*30*6 { //小于半年
return fmt.Sprintf("%d月前", int(diff.Hours()/24/30))
} else if diff.Hours() < 24*365 { //小于1年
return "半年前"
} else {
return t.Format("2006-01-02 15:04:05")
}
}

@ -0,0 +1,101 @@
package stime
import (
"fmt"
"strconv"
"time"
)
// 根据指定时间获取后面的若干天工作日列表
// param baseOn 指定基准时间
// param daysNum 获取工作日的数量
func GetWorkDayList(baseOn *time.Time, daysNum int) []time.Time {
var timeList []time.Time
var basCount = 1
var workDay time.Time
for {
if len(timeList) == daysNum {
break
}
workDay = baseOn.AddDate(0, 0, basCount)
switch workDay.Weekday() {
case time.Saturday:
basCount += 2
continue
case time.Sunday:
basCount++
continue
default:
timeList = append(timeList, workDay)
basCount++
}
}
return timeList
}
// 根据指定时间获取后面的若干天工作日列表
// param baseOn 指定基准时间
// param daysNum 获取工作日的数量
func GetWorkDayStrList(baseOn *time.Time, daysNum int) []string {
var timeList []string
var basCount = 1
var workDay time.Time
for {
if len(timeList) == daysNum {
break
}
workDay = baseOn.AddDate(0, 0, basCount)
switch workDay.Weekday() {
case time.Saturday:
basCount += 2
continue
case time.Sunday:
basCount++
continue
default:
timeList = append(timeList, TimeToString(workDay, Format_Normal_YMD))
basCount++
}
}
return timeList
}
// 获取时间差文字描述
func GetTimeDifferenceDesc(now *time.Time, before *time.Time) string {
if before == nil {
return ""
}
if now.After(*before) {
subTimestamp := now.Unix() - before.Unix()
day := subTimestamp / (3600 * 24)
hour := (subTimestamp - day*3600*24) / 3600
minute := (subTimestamp - day*3600*24 - hour*3600) / 60
second := subTimestamp - day*3600*24 - hour*3600 - minute*60
switch {
case day > 0:
if hour > 0 {
return fmt.Sprintf("%d天%d小时", day, hour)
} else {
return fmt.Sprintf("%d天", day)
}
case hour > 0:
if minute < 10 {
return fmt.Sprintf("%d小时", hour)
} else {
return fmt.Sprintf("%d小时%d", hour, minute)
}
case hour == 0 && minute > 0:
return fmt.Sprintf("%d分钟", minute)
case hour == 0 && minute == 0:
return fmt.Sprintf("%d秒", second)
}
}
return ""
}
// TimeStampToBytes 时间戳转字节
func TimeStampToBytes(stamp int64) []byte {
timeStr := strconv.FormatInt(stamp, 2)
return []byte(timeStr)
}

@ -0,0 +1,12 @@
package stime
import (
"testing"
"time"
)
func TestGetWorkDayStrList(t *testing.T) {
now := time.Now()
result := GetWorkDayStrList(&now, 5)
t.Log(result)
}

@ -0,0 +1,71 @@
/*
* @Author: immortal
* @Date: 2022-03-11 20:55:38
* @LastEditors: immortal
* @LastEditTime: 2022-03-12 14:26:42
* @Description:
* @FilePath: \monitor_env\utils\simpletime\timeTranslate.go
*/
/**
* @Author Puzzle
* @Date 2021/11/18 1:36
**/
package stime
import (
"fmt"
"time"
)
func GetTimestampMillisecond() int64 {
now := time.Now()
return now.UnixNano() / 1e6
}
func StringToTime(strTime string) (*time.Time, error) {
const TIME_LAYOUT = "2006-01-02 15:04:05" //此时间不可更改
timeobj, err := time.ParseInLocation(TIME_LAYOUT, strTime, Loc.Shanghai())
return &timeobj, err
}
func StringToTimeWithFormat(strTime string, timeFormat string) (*time.Time, error) {
timeobj, err := time.ParseInLocation(timeFormat, strTime, Loc.Shanghai())
return &timeobj, err
}
// 去除精确时间后面的小数点
func NowTimeToTime(layout string) *time.Time {
otime := time.Now().Format(layout) //"2006-01-02 15:04:05" and so on
tt, _ := StringToTime(otime)
return tt
}
// 时间之间的转换
func TimeStampToString(value interface{}, after_type string) {
switch value.(type) {
case string:
fmt.Println(value.(string))
case int64:
fmt.Println(value.(int64))
case int32:
fmt.Println(value.(int32))
}
}
func GetAge(birthday time.Time) int {
if birthday.IsZero() {
return 0
}
now := time.Now()
year, month, day := now.Date()
if year == 0 || month == 0 || day == 0 {
return 0
}
age := year - birthday.Year() - 1
//判断年龄
if birthday.Month() < month || birthday.Month() == month && birthday.Day() <= day {
age++
}
return age
}

@ -0,0 +1,26 @@
/*
* @FileName: time_test.go
* @Author: JJXu
* @CreateTime: 2022/2/25 2:37
* @Description:
*/
package stime
import (
"fmt"
"testing"
"time"
)
func TestTime(t *testing.T) {
result := NowTimeToTime(Format_Normal_YMDhms)
fmt.Println(result)
}
func TestGetAge(t *testing.T) {
age := GetAge(time.Date(1991, 3, 6, 0, 0, 0, 0, Loc.Shanghai()))
fmt.Println(age)
if age != 31 {
t.Errorf("want 31 but get %v", age)
}
}

@ -0,0 +1,52 @@
/**
* @Author Puzzle
* @Date 2022/5/20 12:54
**/
package stime
import "time"
func NowWeekDay() string {
var weekday = [7]string{"七", "一", "二", "三", "四", "五", "六"}
week := int(time.Now().Weekday())
return weekday[week]
}
// 获取按年算的周数
func GetYearWeek(t *time.Time) int {
yearDay := t.YearDay()
yearFirstDay := t.AddDate(0, 0, -yearDay+1)
firstDayInWeek := int(yearFirstDay.Weekday())
//今年第一周有几天
firstWeekDays := 1
if firstDayInWeek != 0 {
firstWeekDays = 7 - firstDayInWeek + 1
}
var week int
if yearDay <= firstWeekDays {
week = 1
} else {
week = (yearDay-firstWeekDays)/7 + 2
}
return week
}
// GetWeekDate 获取基准时间范围最最近的某个星期时间
//
// param baseOn: 基准时间
// param weekNum: 中国星期数 1~7
// return *time.Time
func GetWeekDate(baseOn time.Time, weekNum int) *time.Time {
if baseOn.IsZero() || (weekNum <= 0 || weekNum > 7) {
return nil
}
baseDate := time.Date(baseOn.Year(), baseOn.Month(), baseOn.Day(), 0, 0, 0, 0, Loc.Shanghai())
var (
w = int(baseOn.Weekday())
weekDate time.Time
)
weekDate = baseDate.AddDate(0, 0, weekNum-w)
return &weekDate
}

@ -0,0 +1,20 @@
// Package simpletime -----------------------------
// @file : week_test.go
// @author : JJXu
// @contact : wavingbear@163.com
// @time : 2022/8/31 14:57
// -------------------------------------------
package stime
import (
"testing"
"time"
)
func TestGetYearWeek(t *testing.T) {
now := time.Now()
t.Log(GetYearWeek(&now))
var w = int(now.Weekday())
t.Log(now.AddDate(0, 0, -w+1).Weekday())
t.Log(now.AddDate(0, 0, 7-w).Weekday())
}

@ -0,0 +1,210 @@
package util
import (
"bytes"
"errors"
"fmt"
"github.com/fonchain/fonchain-container/pkg/config"
"io"
"mime/multipart"
"net/http"
"reflect"
"strconv"
"strings"
"time"
"github.com/fonchain/fonchain-container/pkg/m"
"github.com/fonchain/utils/objstorage"
uuid "github.com/satori/go.uuid"
)
// IdCardTurnAge 身份证号读取年龄
func IdCardTurnAge(idCard string) int {
var mapmou = map[string]int{"January": 1, "february": 2, "March": 3, "April": 4, "May": 5, "June": 6, "July": 7, "August": 8, "September": 9, "October": 10, "November": 11, "December": 12}
// idCard := "34052419800101001X" //身份证
now := time.Now()
now_year := now.Year() // 年
now_mo := mapmou[now.Month().String()] // 月
now_day := now.Day() // 日
fmt.Println(now_year, now_mo, now_day)
idcard_year, _ := strconv.Atoi(Substr(idCard, 6, 4)) // 年
idcard_mo, _ := strconv.Atoi(Substr(idCard, 10, 2)) // 月
idcard_day, _ := strconv.Atoi(Substr(idCard, 12, 2)) // 日
fmt.Println(idcard_year, idcard_mo, idcard_day)
fmt.Println("idCard:" + idCard)
age := now_year - idcard_year // 如果计算虚岁需这样age := now_year - idcard_year+1
if now_year < idcard_year {
age = 0
} else {
if now_mo < idcard_mo {
age = age - 1
} else {
if now_day < idcard_day {
age = age - 1
}
}
}
fmt.Println("age:", age)
return age
}
func Substr(str string, start, length int) string {
rs := []rune(str)
rl := len(rs)
end := 0
if start < 0 {
start = rl - 1 + start
}
end = start + length
if start > end {
start, end = end, start
}
if start < 0 {
start = 0
}
if start > rl {
start = rl
}
if end < 0 {
end = 0
}
if end > rl {
end = rl
}
return string(rs[start:end])
}
// 封装上传图片到bos然后返回状态和图片的url单张
func UploadToBos(file multipart.File, objName string) (string, error) {
BOSClient, err := objstorage.NewBOS(config.Bos.AK, config.Bos.SK, objstorage.BOS_BJ)
if err != nil {
fmt.Println(err)
}
b := new(strings.Builder)
io.Copy(b, file)
_, err = BOSClient.PutObjectFromBytes(config.Bos.BucketName, objName, []byte(b.String()))
if err != nil {
return "", err
}
url := config.Bos.Url + "/" + objName
return url, nil
}
func UploadToBosUseBytes(raw []byte, objPath string) (string, error) {
BOSClient, err := objstorage.NewBOS(config.Bos.AK, config.Bos.SK, objstorage.BOS_BJ)
if err != nil {
fmt.Println(err)
}
_, err = BOSClient.PutObjectFromBytes(config.Bos.BucketName, objPath, raw)
if err != nil {
return "", err
}
url := config.Bos.Url + "/" + objPath
return url, nil
}
type CopyOption struct {
Src interface{}
Dst interface{}
WhiteFields string
BlackFields string
}
// 反射
func CopyStructSuper(copyOpt CopyOption) {
st := reflect.TypeOf(copyOpt.Src)
sv := reflect.ValueOf(copyOpt.Src)
dt := reflect.TypeOf(copyOpt.Dst)
dv := reflect.ValueOf(copyOpt.Dst)
if st.Kind() == reflect.Ptr { //处理指针
st = st.Elem()
sv = sv.Elem()
}
if dt.Kind() == reflect.Ptr { //处理指针
dt = dt.Elem()
}
if st.Kind() != reflect.Struct || dt.Kind() != reflect.Struct { //如果不是struct类型直接返回dst
return
}
dv = reflect.ValueOf(dv.Interface())
// 遍历TypeOf 类型
for i := 0; i < dt.NumField(); i++ { //通过索引来取得它的所有字段,同时来决定循环的次数
f := dt.Field(i) //通过这个i作为它的索引从0开始来取得它的字段
dVal := dv.Elem().Field(i)
sVal := sv.FieldByName(f.Name)
if copyOpt.WhiteFields != "" {
if !strings.Contains(copyOpt.WhiteFields, fmt.Sprintf(",%s,", f.Name)) {
continue
}
}
if copyOpt.BlackFields != "" {
if strings.Contains(copyOpt.BlackFields, fmt.Sprintf(",%s,", f.Name)) {
continue
}
}
//src数据有效且dst字段能赋值,类型一致
if sVal.IsValid() && dVal.CanSet() && f.Type.Kind() == sVal.Type().Kind() {
dVal.Set(sVal)
}
}
}
func Post(url, data string) (string, error) {
reader := bytes.NewReader([]byte(data))
request, err := http.NewRequest("POST", url, reader)
if err != nil {
return "", err
}
defer request.Body.Close() //程序在使用完回复后必须关闭回复的主体
request.Header.Set("Content-Type", "application/json;charset=UTF-8")
//必须设定该参数,POST参数才能正常提交意思是以json串提交数据
client := http.Client{}
resp, err := client.Do(request) //Do 方法发送请求,返回 HTTP 回复
if err != nil {
return "", err
}
respBytes, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
//byte数组直接转成string优化内存
// str := (*string)(unsafe.Pointer(&respBytes))
return string(respBytes), nil
}
// 生成uid
func GetUid() (uuids string, err error) {
var uid uuid.UUID
if uid, err = uuid.NewV4(); err != nil {
err = errors.New(m.ERROR_UID)
return "", err
}
return uid.String(), nil
}
func GetNativePlaceFromAddress(address string) string {
if address == "" {
return ""
}
runeStr := []rune(address)
var startIndex int
for i, v := range runeStr {
if startIndex == 0 && string(v) != "\"" {
startIndex = i + 2
}
if string(v) == "市" {
return string(runeStr[startIndex : i+1])
}
}
return ""
}

@ -0,0 +1,2 @@
@echo off
protoc -I . -I ./pb --proto_path=. --proto_path=C:\Users\lenovo\go\src --go_out=./pb/container --go-triple_out=./pb/container --govalidators_out=./pb/container --go-meta_out=./pb/container ./pb/container.proto

@ -1,3 +1,9 @@
# fonchain-container 货架服务 # fonchain-container 货架管理微服务
## 项目说明 ## 项目说明
项目包含硬件mcu程序和软件服务端程序。mcu程序基于C++开发,位于[./mcuClients](./mcuClients)目录中,服务端位于[./containerServer](./containerServer)目录中 项目包含硬件mcu程序和软件服务端程序。mcu程序基于C++开发,位于[./src](./src)目录中服务端的mcu控制程序位于[./cmd/internal/embedded](./cmd/internal/embedded)目录中
## 代办
- [ ] 完善ping方法 记录硬件的网络状态。
- [ ] 服务端记录led灯状态如果货柜连接服务端后
### LEDongzh
Loading…
Cancel
Save