Skip to content

Commit 6f55f3c

Browse files
author
chaoyuepan
committed
modernize
1 parent c781d7c commit 6f55f3c

File tree

6 files changed

+52
-41
lines changed

6 files changed

+52
-41
lines changed

main.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ func loadEnv() {
2727
return
2828
}
2929

30-
lines := strings.Split(string(content), "\n")
31-
for _, line := range lines {
30+
lines := strings.SplitSeq(string(content), "\n")
31+
for line := range lines {
3232
line = strings.TrimSpace(line)
3333
if line == "" || strings.HasPrefix(line, "#") {
3434
continue

pkg/agent/agent.go

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"fmt"
66
"log"
7+
"slices"
78
"sync"
89
"time"
910

@@ -201,13 +202,7 @@ func (lm *AgentLifecycleManager) isValidTransition(from, to AgentState) bool {
201202
return false
202203
}
203204

204-
for _, validState := range allowed {
205-
if to == validState {
206-
return true
207-
}
208-
}
209-
210-
return false
205+
return slices.Contains(allowed, to)
211206
}
212207

213208
// UpdateActivity updates the last activity timestamp

pkg/chat/chat.go

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1643,8 +1643,8 @@ func (cs *ChatServer) Start(staticFS fs.FS) error {
16431643

16441644
if token != "" {
16451645
// Validate token
1646-
if strings.HasPrefix(token, "Bearer ") {
1647-
tokenStr := strings.TrimPrefix(token, "Bearer ")
1646+
if after, ok := strings.CutPrefix(token, "Bearer "); ok {
1647+
tokenStr := after
16481648
if _, err := cs.jwtAuth.ValidateToken(tokenStr); err == nil {
16491649
// User is authenticated, serve original index.html
16501650
cs.HandleIndex(w, r, staticFS)
@@ -1780,12 +1780,12 @@ IMPORTANT:
17801780

17811781
// Clean up the decision
17821782
cleanDecision := strings.TrimSpace(decision)
1783-
if strings.HasPrefix(cleanDecision, "```json") {
1784-
cleanDecision = strings.TrimPrefix(cleanDecision, "```json")
1783+
if after, ok := strings.CutPrefix(cleanDecision, "```json"); ok {
1784+
cleanDecision = after
17851785
cleanDecision = strings.TrimSuffix(cleanDecision, "```")
17861786
cleanDecision = strings.TrimSpace(cleanDecision)
1787-
} else if strings.HasPrefix(cleanDecision, "```") {
1788-
cleanDecision = strings.TrimPrefix(cleanDecision, "```")
1787+
} else if after, ok := strings.CutPrefix(cleanDecision, "```"); ok {
1788+
cleanDecision = after
17891789
cleanDecision = strings.TrimSuffix(cleanDecision, "```")
17901790
cleanDecision = strings.TrimSpace(cleanDecision)
17911791
}
@@ -1859,12 +1859,12 @@ IMPORTANT:
18591859

18601860
// Clean up the decision
18611861
cleanDecision := strings.TrimSpace(decision)
1862-
if strings.HasPrefix(cleanDecision, "```json") {
1863-
cleanDecision = strings.TrimPrefix(cleanDecision, "```json")
1862+
if after, ok := strings.CutPrefix(cleanDecision, "```json"); ok {
1863+
cleanDecision = after
18641864
cleanDecision = strings.TrimSuffix(cleanDecision, "```")
18651865
cleanDecision = strings.TrimSpace(cleanDecision)
1866-
} else if strings.HasPrefix(cleanDecision, "```") {
1867-
cleanDecision = strings.TrimPrefix(cleanDecision, "```")
1866+
} else if after, ok := strings.CutPrefix(cleanDecision, "```"); ok {
1867+
cleanDecision = after
18681868
cleanDecision = strings.TrimSuffix(cleanDecision, "```")
18691869
cleanDecision = strings.TrimSpace(cleanDecision)
18701870
}
@@ -1916,7 +1916,7 @@ func (s *ChatServer) HandleHealth(w http.ResponseWriter, r *http.Request) {
19161916
w.Header().Set("Content-Type", "application/json")
19171917
if allHealthy {
19181918
w.WriteHeader(http.StatusOK)
1919-
if err := json.NewEncoder(w).Encode(map[string]interface{}{
1919+
if err := json.NewEncoder(w).Encode(map[string]any{
19201920
"status": "healthy",
19211921
"timestamp": time.Now().UTC(),
19221922
"checks": results,
@@ -1925,7 +1925,7 @@ func (s *ChatServer) HandleHealth(w http.ResponseWriter, r *http.Request) {
19251925
}
19261926
} else {
19271927
w.WriteHeader(http.StatusServiceUnavailable)
1928-
if err := json.NewEncoder(w).Encode(map[string]interface{}{
1928+
if err := json.NewEncoder(w).Encode(map[string]any{
19291929
"status": "unhealthy",
19301930
"timestamp": time.Now().UTC(),
19311931
"checks": results,
@@ -1937,7 +1937,7 @@ func (s *ChatServer) HandleHealth(w http.ResponseWriter, r *http.Request) {
19371937
// Fallback health check
19381938
w.Header().Set("Content-Type", "application/json")
19391939
w.WriteHeader(http.StatusOK)
1940-
if err := json.NewEncoder(w).Encode(map[string]interface{}{
1940+
if err := json.NewEncoder(w).Encode(map[string]any{
19411941
"status": "healthy",
19421942
"timestamp": time.Now().UTC(),
19431943
}); err != nil {
@@ -1960,7 +1960,7 @@ func (s *ChatServer) HandleMetrics(w http.ResponseWriter, r *http.Request) {
19601960

19611961
w.Header().Set("Content-Type", "application/json")
19621962
w.WriteHeader(http.StatusNotFound)
1963-
if err := json.NewEncoder(w).Encode(map[string]interface{}{
1963+
if err := json.NewEncoder(w).Encode(map[string]any{
19641964
"error": "Metrics collection not enabled",
19651965
}); err != nil {
19661966
log.Printf("Warning: Failed to encode metrics error response: %v", err)
@@ -1988,15 +1988,15 @@ func (s *ChatServer) HandleReady(w http.ResponseWriter, r *http.Request) {
19881988
w.Header().Set("Content-Type", "application/json")
19891989
if ready {
19901990
w.WriteHeader(http.StatusOK)
1991-
if err := json.NewEncoder(w).Encode(map[string]interface{}{
1991+
if err := json.NewEncoder(w).Encode(map[string]any{
19921992
"status": "ready",
19931993
"timestamp": time.Now().UTC(),
19941994
}); err != nil {
19951995
log.Printf("Warning: Failed to encode ready response: %v", err)
19961996
}
19971997
} else {
19981998
w.WriteHeader(http.StatusServiceUnavailable)
1999-
if err := json.NewEncoder(w).Encode(map[string]interface{}{
1999+
if err := json.NewEncoder(w).Encode(map[string]any{
20002000
"status": "not ready",
20012001
"timestamp": time.Now().UTC(),
20022002
}); err != nil {
@@ -2007,7 +2007,7 @@ func (s *ChatServer) HandleReady(w http.ResponseWriter, r *http.Request) {
20072007
// Default to ready if no health checker is configured
20082008
w.Header().Set("Content-Type", "application/json")
20092009
w.WriteHeader(http.StatusOK)
2010-
if err := json.NewEncoder(w).Encode(map[string]interface{}{
2010+
if err := json.NewEncoder(w).Encode(map[string]any{
20112011
"status": "ready",
20122012
"timestamp": time.Now().UTC(),
20132013
}); err != nil {
@@ -2018,12 +2018,12 @@ func (s *ChatServer) HandleReady(w http.ResponseWriter, r *http.Request) {
20182018

20192019
// HandleInfo handles server info requests
20202020
func (s *ChatServer) HandleInfo(w http.ResponseWriter, r *http.Request) {
2021-
info := map[string]interface{}{
2021+
info := map[string]any{
20222022
"service": "LangChat Agent",
20232023
"version": "1.0.0",
20242024
"environment": "development", // TODO: Get from config manager
20252025
"timestamp": time.Now().UTC(),
2026-
"features": map[string]interface{}{
2026+
"features": map[string]any{
20272027
"agent_management": s.lifecycleManager != nil,
20282028
"monitoring": s.metricsCollector != nil,
20292029
"health_checks": s.healthChecker != nil,
@@ -2039,16 +2039,16 @@ func (s *ChatServer) HandleInfo(w http.ResponseWriter, r *http.Request) {
20392039
}
20402040

20412041
// Add configuration summary
2042-
info["config"] = map[string]interface{}{
2043-
"server": map[string]interface{}{
2042+
info["config"] = map[string]any{
2043+
"server": map[string]any{
20442044
"host": s.config.Server.Host,
20452045
"port": s.config.Server.Port,
20462046
},
2047-
"agent": map[string]interface{}{
2047+
"agent": map[string]any{
20482048
"max_concurrent": s.config.Agent.MaxConcurrent,
20492049
"max_idle_time": s.config.Agent.MaxIdleTime,
20502050
},
2051-
"monitoring": map[string]interface{}{
2051+
"monitoring": map[string]any{
20522052
"enabled": s.config.Monitoring.Enabled,
20532053
"metrics_port": s.config.Monitoring.MetricsPort,
20542054
},

pkg/config/config.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -385,7 +385,7 @@ func (m *Manager) setFieldValue(field reflect.Value, value string) error {
385385
case reflect.String:
386386
field.SetString(value)
387387
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
388-
if field.Type() == reflect.TypeOf(time.Duration(0)) {
388+
if field.Type() == reflect.TypeFor[time.Duration]() {
389389
duration, err := time.ParseDuration(value)
390390
if err != nil {
391391
return err

pkg/middleware/auth.go

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package middleware
33
import (
44
"context"
55
"net/http"
6+
"slices"
67
"strings"
78
"time"
89

@@ -47,7 +48,7 @@ func (a *AuthMiddleware) GenerateToken(userID, username string, roles []string)
4748

4849
// ValidateToken validates the JWT token and returns the claims
4950
func (a *AuthMiddleware) ValidateToken(tokenString string) (*auth.JWTClaims, error) {
50-
token, err := jwt.ParseWithClaims(tokenString, &auth.JWTClaims{}, func(token *jwt.Token) (interface{}, error) {
51+
token, err := jwt.ParseWithClaims(tokenString, &auth.JWTClaims{}, func(token *jwt.Token) (any, error) {
5152
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
5253
return nil, jwt.ErrSignatureInvalid
5354
}
@@ -151,13 +152,7 @@ func (a *AuthMiddleware) HasRole(ctx context.Context, role string) bool {
151152
return false
152153
}
153154

154-
for _, userRole := range user.Roles {
155-
if userRole == role {
156-
return true
157-
}
158-
}
159-
160-
return false
155+
return slices.Contains(user.Roles, role)
161156
}
162157

163158
// RequireRole creates a middleware that requires the user to have the specified role
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"id": "a9c139cc-ad4f-4bd0-aeb5-09d820f1941e",
3+
"messages": [
4+
{
5+
"id": "06b99b4c-585e-4c9b-90c9-3432f58233a7",
6+
"role": "user",
7+
"content": "介绍Go语言的modernize工具",
8+
"timestamp": "2025-12-23T14:19:47.922278+08:00",
9+
"feedback": ""
10+
},
11+
{
12+
"id": "c57bd41a-2f7e-4504-b0f9-644e2fc1b7bb",
13+
"role": "assistant",
14+
"content": "Go语言的 `modernize` 工具通常是指导一系列帮助将旧版 Go 代码迁移到现代写法(比如适配新语法、修复废弃特性、优化代码结构)的工具链。以下是常见的相关工具和用法,简明介绍:\n\n### 1. **`gofmt` 和 `go fmt`**\n - 基础格式化工具,内置在 Go 中。\n - 示例:\n ```bash\n gofmt -w . # 格式化当前目录所有文件\n ```\n\n### 2. **`go fix`**\n - 自动修复旧版 Go 的废弃语法(如 `go get` 的旧形式)。\n - 示例:\n ```bash\n go fix ./...\n ```\n\n### 3. **`gofumpt`**(第三方)\n - 更严格的格式化工具,基于 `gofmt` 扩展。\n - 安装:\n ```bash\n go install mvdan.cc/gofumpt@latest\n ```\n - 使用:\n ```bash\n gofumpt -w .\n ```\n\n### 4. **`goimports`**(第三方)\n - 自动添加/删除未使用的 imports。\n - 安装:\n ```bash\n go install golang.org/x/tools/cmd/goimports@latest\n ```\n - 使用:\n ```bash\n goimports -w .\n ```\n\n### 5. **`staticcheck`**(第三方)\n - 静态分析工具,检测潜在问题(如废弃 API)。\n - 安装:\n ```bash\n go install honnef.co/go/tools/cmd/staticcheck@latest\n ```\n - 使用:\n ```bash\n staticcheck ./...\n ```\n\n### 6. **迁移到 Go Modules**\n - 如果项目还在用 `GOPATH`,可运行以下命令初始化 Modules:\n ```bash\n go mod init \u003c模块名\u003e\n go mod tidy\n ```\n\n### 总结命令\n```bash\n# 格式化 + 修复\ngofmt -w . \u0026\u0026 go fix ./... \u0026\u0026 goimports -w . \u0026\u0026 go mod tidy\n```\n\n这些工具能高效完成大部分代码现代化工作,根据需求组合使用即可。",
15+
"timestamp": "2025-12-23T14:20:02.467602+08:00",
16+
"feedback": ""
17+
}
18+
],
19+
"created_at": "2025-12-23T14:19:29.55271+08:00",
20+
"updated_at": "2025-12-23T14:20:02.467603+08:00"
21+
}

0 commit comments

Comments
 (0)