重构服务器

This commit is contained in:
kercylan98
2023-04-19 17:13:34 +08:00
parent 45a9d9b4e3
commit 481ccc182a
54 changed files with 946 additions and 1836 deletions

24
utils/file/file.go Normal file
View File

@@ -0,0 +1,24 @@
package file
import "os"
// PathExist 路径是否存在
func PathExist(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
// IsDir 路径是否是文件夹
func IsDir(path string) (bool, error) {
fileInfo, err := os.Stat(path)
if err == nil {
return fileInfo.IsDir(), nil
}
return false, err
}

View File

@@ -1,6 +1,8 @@
package g2d
import "minotaur/utils/g2d/matrix"
import (
"minotaur/utils/g2d/matrix"
)
// NewMatrix 生成特定宽高的二维矩阵
func NewMatrix[T any](width, height int) *matrix.Matrix[T] {

View File

@@ -1,43 +0,0 @@
package middlewares
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"minotaur/utils/log"
"net/http"
"runtime/debug"
)
// Cors 设置跨域
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin") // 请求头部
if origin != "" {
// 接收客户端发送的origin (重要!)
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
// 服务器支持的所有跨域请求的方法
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
// 允许跨域设置可以返回其他子段,可以自定义字段
c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session")
// 允许浏览器(客户端)可以解析的头部 (重要)
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
// 设置缓存时间
// c.Header("Access-Control-Max-Age", "172800")
// 允许客户端传递校验信息比如 cookie (重要)
c.Header("Access-Control-Allow-Credentials", "true")
}
// 允许类型校验
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
defer func() {
if err := recover(); err != nil {
log.Error("Panic info is", zap.Any("err", err), zap.Any("stack\n", string(debug.Stack())))
}
}()
c.Next()
}
}

View File

@@ -1,28 +0,0 @@
package middlewares
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"time"
)
func Logger(logger *zap.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
query := c.Request.URL.RawQuery
c.Next()
cost := time.Since(start)
logger.Info(path,
zap.Int("status", c.Writer.Status()),
zap.String("method", c.Request.Method),
zap.String("path", path),
zap.String("query", query),
zap.String("ip", c.ClientIP()),
zap.String("user-agent", c.Request.UserAgent()),
zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
zap.Duration("cost", cost),
)
}
}

View File

@@ -12,11 +12,6 @@ import (
var (
Logger *zap.Logger
Info func(msg string, fields ...zap.Field)
Warn func(msg string, fields ...zap.Field)
Debug func(msg string, fields ...zap.Field)
Error func(msg string, fields ...zap.Field)
)
const (
@@ -27,11 +22,6 @@ const (
func init() {
Logger = newLogger()
Info = Logger.Info
Warn = Logger.Warn
Debug = Logger.Debug
Error = Logger.Error
}
func newLogger() *zap.Logger {
@@ -94,3 +84,19 @@ func getWriter(filename string, times int32) io.Writer {
}
return hook
}
func Info(msg string, fields ...zap.Field) {
Logger.Info(msg, fields...)
}
func Warn(msg string, fields ...zap.Field) {
Logger.Warn(msg, fields...)
}
func Debug(msg string, fields ...zap.Field) {
Logger.Debug(msg, fields...)
}
func Error(msg string, fields ...zap.Field) {
Logger.Error(msg, fields...)
}

49
utils/runtimes/path.go Normal file
View File

@@ -0,0 +1,49 @@
package runtimes
import (
"log"
"os"
"path"
"path/filepath"
"runtime"
"strings"
)
// GetWorkingDir 获取工作目录绝对路径
func GetWorkingDir() string {
dir := GetExecutablePathByBuild()
if strings.Contains(dir, GetTempDir()) {
return GetExecutablePathByCaller()
}
return dir
}
// GetTempDir 获取系统临时目录
func GetTempDir() string {
dir := os.Getenv("TEMP")
if dir == "" {
dir = os.Getenv("TMP")
}
res, _ := filepath.EvalSymlinks(dir)
return res
}
// GetExecutablePathByBuild 获取当前执行文件绝对路径go build
func GetExecutablePathByBuild() string {
exePath, err := os.Executable()
if err != nil {
log.Fatal(err)
}
res, _ := filepath.EvalSymlinks(filepath.Dir(exePath))
return res
}
// GetExecutablePathByCaller 获取当前执行文件绝对路径go run
func GetExecutablePathByCaller() string {
var abPath string
_, filename, _, ok := runtime.Caller(3)
if ok {
abPath = path.Dir(filename)
}
return abPath
}

37
utils/sole/guid.go Normal file
View File

@@ -0,0 +1,37 @@
package sole
import "sync"
var (
global int64
namespace map[any]int64
mutex sync.Mutex
)
func init() {
namespace = map[any]int64{}
}
func Get() int64 {
global++
return global
}
func GetWith(name any) int64 {
namespace[name]++
return namespace[name]
}
func GetSync() int64 {
mutex.Lock()
defer mutex.Unlock()
global++
return global
}
func GetSyncWith(name any) int64 {
mutex.Lock()
defer mutex.Unlock()
namespace[name]++
return namespace[name]
}

29
utils/sole/sonyflake.go Normal file
View File

@@ -0,0 +1,29 @@
package sole
import "github.com/sony/sonyflake"
var sonyflakeGenerator *sonyflake.Sonyflake
func init() {
sonyflakeGenerator = sonyflake.NewSonyflake(sonyflake.Settings{})
}
// SonyflakeIDE 获取一个雪花id
func SonyflakeIDE() (int64, error) {
id, err := sonyflakeGenerator.NextID()
return int64(id), err
}
// SonyflakeID 获取一个雪花id
func SonyflakeID() int64 {
id, err := sonyflakeGenerator.NextID()
if err != nil {
panic(err)
}
return int64(id)
}
// SonyflakeSetting 配置雪花id生成策略
func SonyflakeSetting(settings sonyflake.Settings) {
sonyflakeGenerator = sonyflake.NewSonyflake(settings)
}

View File

@@ -0,0 +1,162 @@
package synchronization
import "sync"
func NewMap[Key comparable, value any]() *Map[Key, value] {
return &Map[Key, value]{
data: make(map[Key]value),
}
}
type Map[Key comparable, Value any] struct {
lock sync.RWMutex
data map[Key]Value
}
func (slf *Map[Key, Value]) Set(key Key, value Value) {
slf.lock.Lock()
defer slf.lock.Unlock()
slf.data[key] = value
}
func (slf *Map[Key, Value]) Get(key Key) Value {
slf.lock.RLock()
defer slf.lock.RUnlock()
return slf.data[key]
}
func (slf *Map[Key, Value]) Exist(key Key) bool {
slf.lock.RLock()
_, exist := slf.data[key]
slf.lock.RUnlock()
return exist
}
func (slf *Map[Key, Value]) GetExist(key Key) (Value, bool) {
slf.lock.RLock()
value, exist := slf.data[key]
slf.lock.RUnlock()
return value, exist
}
func (slf *Map[Key, Value]) Length() int {
slf.lock.RLock()
defer slf.lock.RUnlock()
return len(slf.data)
}
func (slf *Map[Key, Value]) Delete(key Key) {
slf.lock.Lock()
defer slf.lock.Unlock()
delete(slf.data, key)
}
func (slf *Map[Key, Value]) DeleteGet(key Key) Value {
slf.lock.Lock()
defer slf.lock.Unlock()
v := slf.data[key]
delete(slf.data, key)
return v
}
func (slf *Map[Key, Value]) DeleteGetExist(key Key) (Value, bool) {
slf.lock.Lock()
defer slf.lock.Unlock()
v, exist := slf.data[key]
delete(slf.data, key)
return v, exist
}
func (slf *Map[Key, Value]) DeleteExist(key Key) bool {
slf.lock.Lock()
if _, exist := slf.data[key]; !exist {
slf.lock.Unlock()
return exist
}
delete(slf.data, key)
slf.lock.Unlock()
return true
}
func (slf *Map[Key, Value]) Range(handle func(key Key, value Value)) {
slf.lock.RLock()
defer slf.lock.RUnlock()
for k, v := range slf.data {
key, value := k, v
handle(key, value)
}
}
func (slf *Map[Key, Value]) RangeSkip(handle func(key Key, value Value) bool) {
slf.lock.RLock()
defer slf.lock.RUnlock()
for k, v := range slf.data {
key, value := k, v
if !handle(key, value) {
continue
}
}
}
func (slf *Map[Key, Value]) RangeBreakout(handle func(key Key, value Value) bool) {
slf.lock.RLock()
defer slf.lock.RUnlock()
for k, v := range slf.data {
key, value := k, v
if !handle(key, value) {
break
}
}
}
func (slf *Map[Key, Value]) RangeFree(handle func(key Key, value Value, skip func(), breakout func())) {
var skipExec, breakoutExec bool
var skip = func() {
skipExec = true
}
var breakout = func() {
breakoutExec = true
}
slf.lock.RLock()
defer slf.lock.RUnlock()
for k, v := range slf.data {
key, value := k, v
handle(key, value, skip, breakout)
if skipExec {
continue
}
if breakoutExec {
break
}
}
}
func (slf *Map[Key, Value]) Keys() []Key {
slf.lock.RLock()
var s = make([]Key, 0, len(slf.data))
for k, _ := range slf.data {
s = append(s, k)
}
slf.lock.RUnlock()
return s
}
func (slf *Map[Key, Value]) Slice() []Value {
slf.lock.RLock()
var s = make([]Value, 0, len(slf.data))
for _, v := range slf.data {
s = append(s, v)
}
slf.lock.RUnlock()
return s
}
func (slf *Map[Key, Value]) Map() map[Key]Value {
var m = make(map[Key]Value)
slf.lock.RLock()
for k, v := range slf.data {
m[k] = v
}
slf.lock.RUnlock()
return m
}