Skip to content

Commit

Permalink
refactor(middleware, monitoring, public): streamline metrics handling…
Browse files Browse the repository at this point in the history
… and remove top referers display

- Simplified MetricsMiddleware by removing unnecessary comments and focusing on essential request logging.
- Updated RequestLog structure to exclude the Referer field from JSON serialization, enhancing data privacy.
- Removed top referers tracking and associated HTML/CSS elements to declutter the user interface and improve performance.
- Cleaned up CSS styles related to referers for a more streamlined design.
  • Loading branch information
woodchen-ink committed Dec 1, 2024
1 parent 6a0df0b commit d393337
Show file tree
Hide file tree
Showing 4 changed files with 1 addition and 108 deletions.
4 changes: 0 additions & 4 deletions middleware/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,13 @@ func MetricsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()

// 创建自定义的ResponseWriter来捕获状态码
rw := &responseWriter{
ResponseWriter: w,
statusCode: http.StatusOK,
}

// 处理请求
next.ServeHTTP(rw, r)

// 记录请求数据
duration := time.Since(start)
monitoring.LogRequest(monitoring.RequestLog{
Time: time.Now().Unix(),
Expand All @@ -33,7 +30,6 @@ func MetricsMiddleware(next http.Handler) http.Handler {
StatusCode: rw.statusCode,
Latency: float64(duration.Microseconds()) / 1000,
IP: utils.GetRealIP(r),
Referer: r.Referer(),
})
})
}
Expand Down
51 changes: 1 addition & 50 deletions monitoring/metrics.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package monitoring

import (
"encoding/json"
"runtime"
"strings"
"sync"
"time"
)

Expand All @@ -21,9 +19,6 @@ type SystemMetrics struct {
HeapAlloc uint64 `json:"heap_alloc"`
HeapSys uint64 `json:"heap_sys"`
} `json:"memory_stats"`

// 热门引用来源
TopReferers sync.Map `json:"-"` // 内部使用 sync.Map
}

type RequestLog struct {
Expand All @@ -33,40 +28,15 @@ type RequestLog struct {
StatusCode int `json:"status_code"`
Latency float64 `json:"latency"`
IP string `json:"ip"`
Referer string `json:"referer"`
Referer string `json:"-"`
}

var (
metrics SystemMetrics
startTime = time.Now()
)

func init() {
// 定期清理引用来源
go func() {
ticker := time.NewTicker(5 * time.Minute)
for range ticker.C {
metrics.TopReferers = sync.Map{} // 直接重置
}
}()
}

func LogRequest(log RequestLog) {
// 更新引用来源
if log.Referer != "direct" {
if val, ok := metrics.TopReferers.Load(log.Referer); ok {
metrics.TopReferers.Store(log.Referer, val.(int64)+1)
} else {
metrics.TopReferers.Store(log.Referer, int64(1))
}
} else {
if val, ok := metrics.TopReferers.Load("直接访问"); ok {
metrics.TopReferers.Store("直接访问", val.(int64)+1)
} else {
metrics.TopReferers.Store("直接访问", int64(1))
}
}

// 更新平均延迟 (只关心 API 请求)
if strings.HasPrefix(log.Path, "/pic/") || strings.HasPrefix(log.Path, "/video/") {
metrics.AverageLatency = (metrics.AverageLatency + log.Latency) / 2
Expand All @@ -86,22 +56,3 @@ func CollectMetrics() *SystemMetrics {

return &metrics
}

// 添加 MarshalJSON 方法来正确序列化 TopReferers
func (m *SystemMetrics) MarshalJSON() ([]byte, error) {
type Alias SystemMetrics
referers := make(map[string]int64)

m.TopReferers.Range(func(key, value interface{}) bool {
referers[key.(string)] = value.(int64)
return true
})

return json.Marshal(&struct {
*Alias
TopReferers map[string]int64 `json:"top_referers"`
}{
Alias: (*Alias)(m),
TopReferers: referers,
})
}
36 changes: 0 additions & 36 deletions public/css/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -352,38 +352,6 @@ td a:hover {
color: #2196f3;
}

.referers-list {
margin-top: 15px;
display: grid;
gap: 8px;
width: 100%;
}

.referer-item {
background: rgba(255, 255, 255, 0.05);
padding: 10px 15px;
border-radius: 6px;
display: flex;
justify-content: space-between;
align-items: center;
}

.referer {
color: #999;
max-width: 70%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}

.count {
color: #2196f3;
font-weight: 500;
padding: 2px 8px;
background: rgba(33, 150, 243, 0.1);
border-radius: 4px;
}

.error-message {
background: rgba(255, 0, 0, 0.1);
color: #ff4444;
Expand Down Expand Up @@ -412,10 +380,6 @@ td a:hover {
.metric-value {
font-size: 1em;
}

.referer {
max-width: 60%;
}
}

.main-title {
Expand Down
18 changes: 0 additions & 18 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -286,24 +286,6 @@ <h2>💻 系统状态</h2>
</div>
</div>
</div>
${Object.keys(data.top_referers).length > 0 ? `
<div class="stats-summary">
<div class="stats-header">
<h2>🔗 访问来源</h2>
</div>
<div class="referers-list">
${Object.entries(data.top_referers)
.sort(([,a], [,b]) => b - a)
.map(([referer, count]) => `
<div class="referer-item">
<span class="referer">${referer || '直接访问'}</span>
<span class="count">${count}</span>
</div>
`).join('')}
</div>
</div>
` : ''}
</div>
`;

Expand Down

0 comments on commit d393337

Please sign in to comment.