初始化2

This commit is contained in:
SunYF
2026-08-28 15:06:01 +08:00
parent b34325a16f
commit a9c3fbeb41
537 changed files with 176215 additions and 17 deletions
+49
View File
@@ -0,0 +1,49 @@
package httpx
import (
"net/http"
"os"
"path"
"strings"
)
const basename = "/"
type NotFoundHandler struct {
fs http.FileSystem
fileServer http.Handler
}
// NewNotFoundHandler 静态资源服务:命中即返回文件,否则回退到 index.html(前端 SPA 路由)
func NewNotFoundHandler(fs http.FileSystem) NotFoundHandler {
return NotFoundHandler{
fs: fs,
fileServer: http.FileServer(fs),
}
}
func (n NotFoundHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api/") {
http.Error(w, "not found", http.StatusNotFound)
return
}
filePath := strings.TrimPrefix(path.Clean(r.URL.Path), basename)
if len(filePath) == 0 {
filePath = basename
}
file, err := n.fs.Open(filePath)
switch {
case err == nil:
n.fileServer.ServeHTTP(w, r)
_ = file.Close()
return
case os.IsNotExist(err):
r.URL.Path = "/" // vue app 虚拟路由统一回 index.html
n.fileServer.ServeHTTP(w, r)
return
default:
http.Error(w, "not found", http.StatusNotFound)
return
}
}
+58
View File
@@ -0,0 +1,58 @@
package httpx
import (
"encoding/json"
"net/http"
)
// Resp 统一返回结构
type Resp struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
func writeJSON(w http.ResponseWriter, status int, body any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(body)
}
// Ok 成功
func Ok(w http.ResponseWriter, data any) {
writeJSON(w, http.StatusOK, Resp{Code: 0, Message: "success", Data: data})
}
// OkCode 成功但自定义 message
func OkMessage(w http.ResponseWriter, message string, data any) {
writeJSON(w, http.StatusOK, Resp{Code: 0, Message: message, Data: data})
}
// Fail 业务失败(HTTP 200,业务码非0)
func Fail(w http.ResponseWriter, code int, message string) {
writeJSON(w, http.StatusOK, Resp{Code: code, Message: message})
}
// FailHTTP 直接返回 HTTP 错误
func FailHTTP(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, Resp{Code: status, Message: message})
}
// BadRequest 参数错误
func BadRequest(w http.ResponseWriter, message string) {
writeJSON(w, http.StatusBadRequest, Resp{Code: 400, Message: message})
}
func InternalError(w http.ResponseWriter, message string) {
writeJSON(w, http.StatusInternalServerError, Resp{Code: 500, Message: message})
}
func Unauthorized(w http.ResponseWriter, message string) {
writeJSON(w, http.StatusUnauthorized, Resp{Code: 401, Message: message})
}
// ParseJSON 解析请求体
func ParseJSON(r *http.Request, v any) error {
dec := json.NewDecoder(r.Body)
return dec.Decode(v)
}
+16
View File
@@ -0,0 +1,16 @@
package logx
// LogConf 按天日志配置
type LogConf struct {
Level string `json:",default=INFO"`
Format string `json:",default=text"`
TimeFormat string `json:",default=2006-01-02 15:04:05"`
Filename string `json:",default=bj_power_mes.log"`
Daily bool `json:",default=true"`
MaxSize int `json:",default=100"`
MaxBackups int `json:",default=10"`
MaxAge int `json:",default=30"`
Compress bool `json:",default=true"`
Console bool `json:",default=true"`
AddSource bool `json:",default=false"`
}
+95
View File
@@ -0,0 +1,95 @@
package logx
import (
"io"
"os"
"path/filepath"
"strings"
"sync"
"time"
"gopkg.in/natefinch/lumberjack.v2"
)
// dailyWriter 按天滚动的日志写入器:文件名 base-2006-01-02.log,跨天自动切换;
// 超过 MaxAge 天的日志文件在跨天时清理。
type dailyWriter struct {
mu sync.Mutex
conf LogConf
date string
lj *lumberjack.Logger
}
func newDailyWriter(conf LogConf) *dailyWriter {
return &dailyWriter{conf: conf}
}
func (w *dailyWriter) filename(date string) string {
ext := filepath.Ext(w.conf.Filename)
base := strings.TrimSuffix(w.conf.Filename, ext)
return base + "-" + date + ext
}
func (w *dailyWriter) Write(p []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
today := time.Now().Format("2006-01-02")
if w.lj == nil || today != w.date {
if w.lj != nil {
_ = w.lj.Close()
}
w.date = today
w.lj = &lumberjack.Logger{
Filename: w.filename(today),
MaxSize: w.conf.MaxSize,
MaxBackups: w.conf.MaxBackups,
MaxAge: w.conf.MaxAge,
Compress: w.conf.Compress,
}
w.cleanup()
}
return w.lj.Write(p)
}
func (w *dailyWriter) Close() error {
w.mu.Lock()
defer w.mu.Unlock()
if w.lj != nil {
return w.lj.Close()
}
return nil
}
// cleanup 清理超过 MaxAge 天的按天日志文件
func (w *dailyWriter) cleanup() {
if w.conf.MaxAge <= 0 {
return
}
dir := filepath.Dir(w.conf.Filename)
ext := filepath.Ext(w.conf.Filename)
base := strings.TrimSuffix(filepath.Base(w.conf.Filename), ext)
entries, err := os.ReadDir(dir)
if err != nil {
return
}
cutoff := time.Now().AddDate(0, 0, -w.conf.MaxAge)
for _, e := range entries {
if e.IsDir() || !strings.HasPrefix(e.Name(), base+"-") || !strings.HasSuffix(e.Name(), ext) {
continue
}
datePart := strings.TrimSuffix(strings.TrimPrefix(e.Name(), base+"-"), ext)
t, err := time.ParseInLocation("2006-01-02", datePart, time.Local)
if err != nil {
continue
}
if t.Before(cutoff) {
_ = os.Remove(filepath.Join(dir, e.Name()))
}
}
}
var (
_ io.WriteCloser = (*dailyWriter)(nil)
_ io.Writer = (*dailyWriter)(nil)
)
+128
View File
@@ -0,0 +1,128 @@
package logx
import (
"context"
"fmt"
"io"
"log/slog"
"os"
"path"
"path/filepath"
"strings"
"github.com/zeromicro/go-zero/core/logx"
"gopkg.in/natefinch/lumberjack.v2"
)
var workdir, _ = filepath.Abs(filepath.Dir(os.Args[0]))
// Logger 包装 slog,并适配 go-zero 的 logx.Writer(按天日志)
type Logger struct {
*slog.Logger
}
func SetDefault(logger *Logger) {
slog.SetDefault(logger.Logger)
}
// NewLogger 按配置创建按天日志
func NewLogger(conf LogConf) *Logger {
logLevel := slog.LevelInfo
switch strings.ToLower(conf.Level) {
case "error":
logLevel = slog.LevelError
case "warn":
logLevel = slog.LevelWarn
case "debug":
logLevel = slog.LevelDebug
}
if !strings.Contains(conf.TimeFormat, "2006") {
conf.TimeFormat = "2006-01-02 15:04:05"
}
if !path.IsAbs(conf.Filename) {
conf.Filename = filepath.Join(workdir, conf.Filename)
}
var fileWriter io.Writer
if conf.Daily {
fileWriter = newDailyWriter(conf)
} else {
fileWriter = &lumberjack.Logger{
Filename: conf.Filename,
MaxSize: conf.MaxSize,
MaxBackups: conf.MaxBackups,
MaxAge: conf.MaxAge,
Compress: conf.Compress,
}
}
var writer io.Writer = fileWriter
if conf.Console {
writer = io.MultiWriter(writer, os.Stdout)
}
opts := &slog.HandlerOptions{Level: logLevel, AddSource: conf.AddSource}
var h slog.Handler
if strings.EqualFold(conf.Format, "json") {
h = slog.NewJSONHandler(writer, opts)
} else {
h = slog.NewTextHandler(writer, opts)
}
return &Logger{Logger: slog.New(h)}
}
func (l *Logger) Close() error {
return nil
}
func (l *Logger) buildAttrs(fields []logx.LogField) []slog.Attr {
attrs := make([]slog.Attr, 0, len(fields))
for _, f := range fields {
attrs = append(attrs, slog.Any(f.Key, f.Value))
}
return attrs
}
func (l *Logger) logAttrs(level slog.Level, msg string, attrs ...slog.Attr) {
l.Logger.LogAttrs(context.Background(), level, msg, attrs...)
}
// --- 实现 logx.Writer 接口 ---
func (l *Logger) Write(p []byte) (int, error) {
l.logAttrs(slog.LevelInfo, strings.TrimSpace(string(p)))
return len(p), nil
}
func (l *Logger) Alert(v any) {
l.logAttrs(slog.LevelError, fmt.Sprint(v))
}
func (l *Logger) Debug(v any, fields ...logx.LogField) {
l.logAttrs(slog.LevelDebug, fmt.Sprint(v), l.buildAttrs(fields)...)
}
func (l *Logger) Error(v any, fields ...logx.LogField) {
l.logAttrs(slog.LevelError, fmt.Sprint(v), l.buildAttrs(fields)...)
}
func (l *Logger) Info(v any, fields ...logx.LogField) {
l.logAttrs(slog.LevelInfo, fmt.Sprint(v), l.buildAttrs(fields)...)
}
func (l *Logger) Severe(v any) {
l.logAttrs(slog.LevelError, fmt.Sprint(v))
}
func (l *Logger) Slow(v any, fields ...logx.LogField) {
l.logAttrs(slog.LevelWarn, fmt.Sprint(v), l.buildAttrs(fields)...)
}
func (l *Logger) Stack(v any) {
l.logAttrs(slog.LevelError, fmt.Sprintf("%+v", v))
}
func (l *Logger) Stat(v any, fields ...logx.LogField) {
l.logAttrs(slog.LevelInfo, fmt.Sprint(v), l.buildAttrs(fields)...)
}
+46
View File
@@ -0,0 +1,46 @@
package tokenx
import (
"errors"
"fmt"
"time"
"github.com/golang-jwt/jwt/v4"
)
// Claims JWT 自定义负载
type Claims struct {
UserId int `json:"userId"`
Username string `json:"username"`
Name string `json:"name"`
RoleId int `json:"roleId"`
RoleCode string `json:"roleCode"`
RoleName string `json:"roleName"`
jwt.RegisteredClaims
}
// Issue 签发 JWT
func Issue(secret string, expire time.Duration, c Claims) (string, error) {
c.IssuedAt = jwt.NewNumericDate(time.Now())
c.ExpiresAt = jwt.NewNumericDate(time.Now().Add(expire))
c.Subject = fmt.Sprintf("%d", c.UserId)
t := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
return t.SignedString([]byte(secret))
}
// Parse 校验 JWT 并返回负载
func Parse(secret, tokenStr string) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(t *jwt.Token) (any, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, errors.New("unexpected signing method")
}
return []byte(secret), nil
})
if err != nil {
return nil, err
}
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
return claims, nil
}
return nil, errors.New("invalid token")
}