init project

This commit is contained in:
admin committed 2025-12-05 17:23:29 +08:00
commit d63cc8d9f5
33 files changed
+1529

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
package configs
import (
"encoding/json"
"os"
)
func Load(path string, c interface{}) error {
data, err := os.ReadFile(path)
if err != nil {
return err
}
if err := json.Unmarshal(data, c); err != nil {
return err
}
return nil
}
+57
View File
@@ -0,0 +1,57 @@
package logger
import (
"context"
log "github.com/sirupsen/logrus"
)
func Trace(ctx context.Context, keyword string, args ...interface{}) {
log.WithFields(WithContext(ctx)).WithField("keyword", keyword).Trace(args...)
}
func Debug(ctx context.Context, keyword string, args ...interface{}) {
log.WithFields(WithContext(ctx)).WithField("keyword", keyword).Debug(args...)
}
func Info(ctx context.Context, keyword string, args ...interface{}) {
log.WithFields(WithContext(ctx)).WithField("keyword", keyword).Info(args...)
}
func Warn(ctx context.Context, keyword string, args ...interface{}) {
log.WithFields(WithContext(ctx)).WithField("keyword", keyword).Warn(args...)
}
func Error(ctx context.Context, keyword string, args ...interface{}) {
log.WithFields(WithContext(ctx)).WithField("keyword", keyword).Error(args...)
}
func Tracef(ctx context.Context, keyword, format string, args ...interface{}) {
log.WithFields(WithContext(ctx)).WithField("keyword", keyword).Tracef(format, args...)
}
func Debugf(ctx context.Context, keyword, format string, args ...interface{}) {
log.WithFields(WithContext(ctx)).WithField("keyword", keyword).Debugf(format, args...)
}
func Infof(ctx context.Context, keyword, format string, args ...interface{}) {
log.WithFields(WithContext(ctx)).WithField("keyword", keyword).Infof(format, args...)
}
func Warnf(ctx context.Context, keyword, format string, args ...interface{}) {
log.WithFields(WithContext(ctx)).WithField("keyword", keyword).Warnf(format, args...)
}
func Errorf(ctx context.Context, keyword, format string, args ...interface{}) {
log.WithFields(WithContext(ctx)).WithField("keyword", keyword).Errorf(format, args...)
}
func WithContext(ctx context.Context) log.Fields {
logFields := log.Fields{}
if ctx.Value("req_id") != nil {
if v, ok := ctx.Value("req_id").(string); ok {
logFields["metadata.req_id"] = v
}
}
return logFields
}
+77
View File
@@ -0,0 +1,77 @@
package logic
import (
"context"
"time"
"git.xiaotuo.co/micro/skeleton/internal/queue/jetstream"
"git.xiaotuo.co/pkg/go-plugins/logger"
log "github.com/sirupsen/logrus"
)
type MessageLogic struct {
}
func newMessageLogic() MessageLogic {
return MessageLogic{}
}
func (lgc MessageLogic) jetStreamPublish(ctx context.Context, topic string, body []byte) (err error) {
log.WithFields(logger.WithContext(ctx)).
WithField("keyword", "nats_send").
WithField("topic", topic).
WithField("body", string(body)).
Debug("start")
ack, err := Resources.JetStreamBroker.PublishMsg(jetstream.NewMsg(ctx, topic, body))
if err != nil {
log.WithFields(logger.WithContext(ctx)).
WithField("keyword", "nats_send").
WithField("topic", topic).
WithField("body", string(body)).
Errorf("failed: %v", err)
} else {
log.WithFields(logger.WithContext(ctx)).
WithField("keyword", "nats_send").
WithField("topic", topic).
WithField("body", string(body)).
WithField("ack_sequence", ack.Sequence).
WithField("ack_duplicate", ack.Duplicate).
Debugf("success")
}
return err
}
func (lgc MessageLogic) QueueReceiveStartLog(ctx context.Context, topic string, payload []byte, reply string) {
log.WithFields(logger.WithContext(ctx)).
WithField("keyword", "nats_receive").
WithField("topic", topic).
WithField("body", string(payload)).
WithField("reply", reply).
Debug("start")
}
func (lgc MessageLogic) QueueReceiveEndLog(ctx context.Context, topic string, err error, startTime time.Time, notifyTime, maxTime time.Duration) {
runTime := time.Now().Unix() - startTime.Unix()
slow := false
if float64(runTime) >= notifyTime.Seconds() {
slow = true
}
if err != nil {
log.WithFields(logger.WithContext(ctx)).
WithField("keyword", "nats_receive").
WithField("topic", topic).
WithField("run_time", runTime).
WithField("max_time", maxTime.Seconds()).
WithField("slow", slow).
Errorf("failed: %v", err)
return
}
log.WithFields(logger.WithContext(ctx)).
WithField("keyword", "nats_receive").
WithField("topic", topic).
WithField("run_time", runTime).
WithField("max_time", maxTime.Seconds()).
WithField("slow", slow).
Debugf("success")
return
}
+68
View File
@@ -0,0 +1,68 @@
package logic
import (
"git.xiaotuo.co/micro/skeleton/internal/storage"
"github.com/nats-io/nats.go"
)
var Resources *resources
type resources struct {
Env string
Server string
JetStreamBroker nats.JetStreamContext
MessageLogic MessageLogic
}
func Init(opts ...Option) error {
options := &Options{}
for _, o := range opts {
o(options)
}
Resources = &resources{
Env: options.env,
Server: options.server,
JetStreamBroker: options.jetStreamBr,
MessageLogic: newMessageLogic(),
}
return nil
}
type Option func(o *Options)
type Options struct {
env string
server string
etcdServer string
st *storage.Storage
jetStreamBr nats.JetStreamContext
tiktokAuthGateway string
}
func WithEnv(env string) Option {
return func(o *Options) {
o.env = env
}
}
func WithStorage(st *storage.Storage) Option {
return func(o *Options) {
o.st = st
}
}
func WithEtcdServer(etcdServer string) Option {
return func(o *Options) {
o.etcdServer = etcdServer
}
}
func WithJetStreamBroker(br nats.JetStreamContext) Option {
return func(o *Options) {
o.jetStreamBr = br
}
}
+32
View File
@@ -0,0 +1,32 @@
package jetstream
import (
"context"
"github.com/nats-io/nats.go"
)
func NewContext(msg *nats.Msg) context.Context {
ctx := context.Background()
ctx = context.WithValue(ctx, "req_id", msg.Header.Get("req_id"))
return ctx
}
func NewMsg(ctx context.Context, subject string, data []byte) *nats.Msg {
header := nats.Header{}
header.Set("req_id", getContextValue(ctx, "req_id"))
return &nats.Msg{
Subject: subject,
Data: data,
Header: header,
}
}
func getContextValue(ctx context.Context, keyword string) string {
if ctx.Value(keyword) != nil {
if v, ok := ctx.Value(keyword).(string); ok {
return v
}
}
return ""
}
+58
View File
@@ -0,0 +1,58 @@
package jetstream
import (
"fmt"
nats "github.com/nats-io/nats.go"
log "github.com/sirupsen/logrus"
)
type Config struct {
Addr string `json:"addr"`
Token string `json:"token"`
}
type JetStream struct {
nats.JetStreamContext
nc *nats.Conn
}
func NewJetStreamBroker(conf Config) (*JetStream, error) {
nc, err := nats.Connect(conf.Addr, nats.Token(conf.Token),
nats.DisconnectErrHandler(func(conn *nats.Conn, err error) {
log.Errorf("jetStream disconnect: %v", err)
}),
nats.ReconnectHandler(func(conn *nats.Conn) {
log.Infof("jetStream reconnect")
}),
nats.ClosedHandler(func(conn *nats.Conn) {
log.Infof("jetStream closed")
}),
nats.DiscoveredServersHandler(func(conn *nats.Conn) {
log.Infof("jetStream discovered")
}),
nats.ErrorHandler(func(conn *nats.Conn, subscription *nats.Subscription, e error) {
subDesc := ""
if subscription != nil {
subDesc = fmt.Sprintf(" subject:%s queue:%s", subscription.Subject, subscription.Queue)
}
log.Errorf("jetStream%s err:%v", subDesc, e)
}),
)
if err != nil {
return nil, err
}
js, err := nc.JetStream()
if err != nil {
return nil, err
}
log.Infof("jetStream Addr: %s", conf.Addr)
return &JetStream{
nc: nc,
JetStreamContext: js,
}, nil
}
func (c *JetStream) Close() {
c.nc.Close()
}
+77
View File
@@ -0,0 +1,77 @@
package crontab
import (
"context"
"fmt"
"git.xiaotuo.co/micro/skeleton/internal/runtime"
"git.xiaotuo.co/micro/skeleton/pkg/util"
"git.xiaotuo.co/pkg/tool/stringx"
"github.com/robfig/cron/v3"
log "github.com/sirupsen/logrus"
)
type Crontab struct {
options *runtime.Options
exit context.CancelFunc
}
func NewCrontab() *Crontab {
ctx, cancel := context.WithCancel(context.Background())
opts := &runtime.Options{
ID: stringx.MakeUUID(),
Type: "crontab",
Context: ctx,
}
return &Crontab{
options: opts,
exit: cancel,
}
}
func (m *Crontab) Init(opts ...runtime.Option) error {
for _, o := range opts {
o(m.options)
}
return nil
}
func (m *Crontab) Start() error {
log.Infof("crontab %s Start...", m.String())
defer log.Infof("crontab Exit...")
c := cron.New(cron.WithSeconds())
// _, _ = c.AddJob("10/* * * * * *", Job(func() { // 每天 10s 执行
//
// }))
c.Start()
log.Infof("crontab start")
<-m.options.Context.Done()
log.Infof("crontab done")
c.Stop()
return nil
}
func (m *Crontab) Stop() error {
m.exit()
return nil
}
func (m *Crontab) String() string {
return fmt.Sprintf("%s://%s", m.options.Type, m.options.ID)
}
func Job(fn func()) cron.Job {
return cron.NewChain(cron.SkipIfStillRunning(cron.DefaultLogger)).Then(cron.FuncJob(fn))
}
func newContext() context.Context {
ctx := context.Background()
ctx = context.WithValue(ctx, "req_id", util.MakeRequestID())
return ctx
}
+51
View File
@@ -0,0 +1,51 @@
package monitor
import (
"context"
"fmt"
"git.xiaotuo.co/micro/skeleton/internal/runtime"
"git.xiaotuo.co/pkg/tool/stringx"
)
type monitor struct {
options *runtime.Options
exit context.CancelFunc
}
func NewMonitor() runtime.Runtime {
ctx, cancel := context.WithCancel(context.Background())
opts := &runtime.Options{
ID: stringx.MakeUUID(),
Type: "monitor",
Context: ctx,
}
return &monitor{
options: opts,
exit: cancel,
}
}
func (m *monitor) Init(opts ...runtime.Option) error {
for _, o := range opts {
o(m.options)
}
return nil
}
func (m *monitor) Start() error {
select {
case <-m.options.Context.Done():
return nil
}
}
func (m *monitor) Stop() error {
m.exit()
return nil
}
func (m *monitor) String() string {
return fmt.Sprintf("%s://%s", m.options.Type, m.options.ID)
}
+36
View File
@@ -0,0 +1,36 @@
package runtime
import (
"context"
)
type Option func(o *Options)
type Options struct {
ID string
Type string
// 自定义参数
Context context.Context
}
func WithID(id string) Option {
return func(o *Options) {
o.ID = id
}
}
func WithType(t string) Option {
return func(o *Options) {
o.Type = t
}
}
func SetRuntimeOption(k, v interface{}) Option {
return func(o *Options) {
if o.Context == nil {
o.Context = context.Background()
}
o.Context = context.WithValue(o.Context, k, v)
}
}
+12
View File
@@ -0,0 +1,12 @@
package runtime
type Runtime interface {
// Init initializes runtime
Init(...Option) error
// Start starts the runtime
Start() error
// Stop shuts down the runtime
Stop() error
// String defines the runtime implementation
String() string
}
+50
View File
@@ -0,0 +1,50 @@
package server
import (
"context"
"fmt"
"strconv"
"git.xiaotuo.co/pkg/go-plugins/grpc/metax"
)
func GetBizId(ctx context.Context) (int64, error) {
bizId := getContextValue(ctx, "biz_id")
if bizId == "" {
return 0, fmt.Errorf("biz_id_is_empty")
}
return strconv.ParseInt(bizId, 10, 64)
}
func NewContext(ctx context.Context) (context.Context, error) {
ctx = metax.TransparentContext(ctx)
reqId, exists, err := metax.GetReqId(ctx)
if err != nil {
return ctx, fmt.Errorf("req_id_parse_fail")
}
if !exists {
return ctx, fmt.Errorf("req_id_not_found")
}
ctx = context.WithValue(ctx, "req_id", reqId)
bizId, exists, err := metax.GetBizId(ctx)
if err != nil {
return ctx, fmt.Errorf("biz_id_parse_fail")
}
if !exists {
return ctx, fmt.Errorf("biz_id_not_found")
}
ctx = context.WithValue(ctx, "biz_id", bizId)
return ctx, nil
}
func getContextValue(ctx context.Context, keyword string) string {
if ctx.Value(keyword) != nil {
if v, ok := ctx.Value(keyword).(string); ok {
return v
}
}
return ""
}
+146
View File
@@ -0,0 +1,146 @@
package cache
import (
"context"
"errors"
"time"
"git.xiaotuo.co/micro/skeleton/internal/logger"
"github.com/go-redis/redis"
)
type BaseCache struct {
rs *redis.Client
isLog bool
}
func (c *BaseCache) exists(ctx context.Context, key string) (bool, error) {
value, err := c.rs.Exists(key).Result()
if errors.Is(err, redis.Nil) {
if c.isLog {
logger.Debugf(ctx, "redis_exists", "key: %s, not_found", key)
}
return false, nil
}
if err != nil {
if c.isLog {
logger.Errorf(ctx, "redis_exists", "key: %s, err: %v", key, err)
}
return false, err
}
exists := value > 0
if c.isLog {
logger.Debugf(ctx, "redis_exists", "key: %s, exists", key)
}
return exists, nil
}
func (c *BaseCache) get(ctx context.Context, key string) (string, error) {
value, err := c.rs.Get(key).Result()
if err != nil {
if c.isLog {
logger.Errorf(ctx, "redis_get", "key: %s, err: %v", key, err)
}
return "", err
}
if c.isLog {
logger.Debugf(ctx, "redis_get", "key: %s, value: %s", key, value)
}
return value, nil
}
func (c *BaseCache) set(ctx context.Context, key string, value interface{}, expire time.Duration) (string, error) {
result, err := c.rs.Set(key, value, expire).Result()
if err != nil {
if c.isLog {
logger.Errorf(ctx, "redis_set", "key: %s, value: %v, err: %v", key, value, err)
}
return "", err
}
if c.isLog {
logger.Debugf(ctx, "redis_set", "key: %s, value: %v", key, value)
}
return result, nil
}
func (c *BaseCache) del(ctx context.Context, key string) (int64, error) {
affect, err := c.rs.Del(key).Result()
if err != nil {
if c.isLog {
logger.Errorf(ctx, "redis_del", "key: %s, err: %v", key, err)
}
return 0, err
}
if c.isLog {
logger.Debugf(ctx, "redis_del", "key: %s, affect: %v", key, affect)
}
return affect, nil
}
func (c *BaseCache) push(ctx context.Context, key string, values ...interface{}) (int64, error) {
affect, err := c.rs.LPush(key, values...).Result()
if err != nil {
if c.isLog {
logger.Errorf(ctx, "redis_lpush", "key: %s, err: %v", key, err)
}
return 0, err
}
if c.isLog {
logger.Debugf(ctx, "redis_lpush", "key: %s, values: %v, affect: %v", key, values, affect)
}
return affect, nil
}
func (c *BaseCache) pop(ctx context.Context, key string) (string, error) {
value, err := c.rs.RPop(key).Result()
if errors.Is(err, redis.Nil) {
if c.isLog {
logger.Tracef(ctx, "redis_rpop", "key: %s null", key)
}
return "", err
}
if err != nil {
if c.isLog {
logger.Errorf(ctx, "redis_rpop", "key: %s, err: %v", key, err)
}
return "", err
}
if c.isLog {
logger.Debugf(ctx, "redis_rpop", "key: %s, value: %v", key, value)
}
return value, nil
}
func (c *BaseCache) length(ctx context.Context, key string) (int64, error) {
l, err := c.rs.LLen(key).Result()
if errors.Is(err, redis.Nil) {
if c.isLog {
logger.Debugf(ctx, "redis_llen", "key: %s null", key)
}
return 0, nil
}
if err != nil {
if c.isLog {
logger.Errorf(ctx, "redis_llen", "key: %s, err: %v", key, err)
}
return 0, err
}
if c.isLog {
logger.Debugf(ctx, "redis_llen", "key: %s, length: %v", key, l)
}
return l, nil
}
func (c *BaseCache) lock(ctx context.Context, key, value string, expire time.Duration) (bool, error) {
result, err := c.rs.SetNX(key, value, expire).Result()
if err != nil {
if c.isLog {
logger.Errorf(ctx, "redis_setnx", "key: %s, err: %v", key, err)
}
return false, err
}
if c.isLog {
logger.Debugf(ctx, "redis_setnx", "key: %s, result: %t", key, result)
}
return result, nil
}
+1
View File
@@ -0,0 +1 @@
package cache
+21
View File
@@ -0,0 +1,21 @@
package storage
type Config struct {
Mysql ConfigMysql `json:"mysql"`
Redis ConfigRedis `json:"redis"`
}
type ConfigMysql struct {
DB string `json:"db"`
Debug bool `json:"debug"`
ShowSQL bool `json:"show_sql"`
MaxOpenConn int `json:"max_open_conn"`
MaxIdleConn int `json:"max_idle_conn"`
ConnMaxLifetime int `json:"conn_max_life_time"`
}
type ConfigRedis struct {
Addr string `json:"addr"`
Auth string `json:"auth"`
DB int `json:"db"`
}
+8
View File
@@ -0,0 +1,8 @@
package model
type BaseModel struct {
Id int64 `json:"id" xorm:"pk autoincr 'id'"`
CreatedAt int64 `json:"created_at" xorm:"created"`
UpdatedAt int64 `json:"updated_at" xorm:"updated"`
DeletedAt int64 `json:"deleted_at" xorm:"deleted notnull"`
}
+74
View File
@@ -0,0 +1,74 @@
package storage
import (
"errors"
"fmt"
"time"
"github.com/go-redis/redis"
xormxlog "git.xiaotuo.co/pkg/go-plugins/xormx/log"
_ "github.com/go-sql-driver/mysql"
log "github.com/sirupsen/logrus"
"xorm.io/xorm"
)
var (
DefaultMaxOpenConn = 10
DefaultMaxIdleConn = 5
DefaultConnMaxLifetime = 1
)
type Storage struct {
engine *xorm.Engine
}
func NewStorage(conf Config) (*Storage, error) {
rs := redis.NewClient(&redis.Options{
Addr: conf.Redis.Addr,
Password: conf.Redis.Auth,
DB: conf.Redis.DB,
})
if _, err := rs.Ping().Result(); err != nil {
return nil, fmt.Errorf("redis.Ping: %v", err)
}
log.Infof("redis addr: %s, db: %d", conf.Redis.Addr, conf.Redis.DB)
if len(conf.Mysql.DB) == 0 {
return nil, errors.New("db init failed: 数据库配置项为空")
}
if conf.Mysql.MaxIdleConn == 0 {
conf.Mysql.MaxIdleConn = DefaultMaxIdleConn
}
if conf.Mysql.MaxOpenConn == 0 {
conf.Mysql.MaxOpenConn = DefaultMaxOpenConn
}
if conf.Mysql.ConnMaxLifetime == 0 {
conf.Mysql.ConnMaxLifetime = DefaultConnMaxLifetime
}
engine, err := xorm.NewEngine("mysql", conf.Mysql.DB)
if err != nil {
return nil, fmt.Errorf("NewEngine: %v", err)
}
log.Infof("mysql addr: %s", xormxlog.SafeAddr(conf.Mysql.DB))
engine.SetMaxOpenConns(conf.Mysql.MaxOpenConn)
engine.SetMaxIdleConns(conf.Mysql.MaxIdleConn)
engine.SetConnMaxLifetime(time.Hour * time.Duration(conf.Mysql.ConnMaxLifetime))
if conf.Mysql.ShowSQL {
engine.SetLogger(xormxlog.NewXormxLogger())
engine.ShowSQL(true)
}
// redisLog := conf.Mysql.ShowSQL
return &Storage{
engine: engine,
}, nil
}
func (s *Storage) NewSession() *xorm.Session {
return s.engine.NewSession()
}
type TransactionClosure func(tx *xorm.Session) error