refactor: separate backend domains and storage adapters
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"kra/internal/server/httpx"
|
||||
"kra/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func EmailErrorAlert(service *service.EmailService, logger *slog.Logger) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if strings.Contains(c.Request.URL.Path, "/email/") {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
writer := &captureWriter{ResponseWriter: c.Writer}
|
||||
c.Writer = writer
|
||||
started := time.Now()
|
||||
c.Next()
|
||||
failed := c.Writer.Status() >= 400
|
||||
if !failed {
|
||||
var result struct {
|
||||
Code int `json:"code"`
|
||||
}
|
||||
failed = json.Unmarshal(writer.body.Bytes(), &result) == nil && result.Code != httpx.CodeSuccess
|
||||
}
|
||||
if !failed {
|
||||
return
|
||||
}
|
||||
username := "Unknown"
|
||||
if claims := Claims(c); claims != nil && claims.Username != "" {
|
||||
username = claims.Username
|
||||
}
|
||||
subject := fmt.Sprintf("%s %s 调用 %s 报错", username, c.ClientIP(), c.Request.URL.Path)
|
||||
body := bytes.NewBuffer(nil)
|
||||
fmt.Fprintf(body, "请求方式:%s<br>请求路径:%s<br>状态码:%d<br>耗时:%s<br>错误响应:<pre>%s</pre>", c.Request.Method, c.Request.URL.Path, c.Writer.Status(), time.Since(started), redactJSON(writer.body.Bytes()))
|
||||
if err := service.Alert(c.Request.Context(), subject, body.String()); err != nil && logger != nil {
|
||||
logger.Error("send HTTP error email", "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user