refactor(server): decouple services and improve architecture
- Introduce interfaces for all major services (JWT, PostAI, Comment, Message, Notification, QRCodeLogin, Upload, Vote, etc.) to support dependency inversion. - Move query parameters from `internal/dto` to a new `internal/query` package to separate request payloads from data transfer objects. - Refactor `internal/router` to use embedded `RouterDeps` for cleaner dependency management. - Decouple handlers from repositories by injecting services instead of direct repository access, ensuring proper layering. - Improve database initialization by moving it from `internal/model` to `internal/database`. - Optimize message decryption by implementing a more efficient `BatchDecrypt` method in `MessageEncryptor` using a worker pool. - Enhance error handling and security by implementing fail-fast checks for encryption key length during startup. - Clean up unused code, including the `avatar` package and several unused DTOs.
This commit is contained in:
@@ -1,115 +0,0 @@
|
||||
package avatar
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// 预定义一组好看的颜色
|
||||
var colors = []string{
|
||||
"#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4",
|
||||
"#FFEAA7", "#DDA0DD", "#98D8C8", "#F7DC6F",
|
||||
"#BB8FCE", "#85C1E9", "#F8B500", "#00CED1",
|
||||
"#E74C3C", "#3498DB", "#2ECC71", "#9B59B6",
|
||||
"#1ABC9C", "#F39C12", "#E67E22", "#16A085",
|
||||
}
|
||||
|
||||
// SVG模板
|
||||
const svgTemplate = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="%d" height="%d">
|
||||
<rect width="100" height="100" fill="%s"/>
|
||||
<text x="50" y="50" font-family="Arial, sans-serif" font-size="40" font-weight="bold" fill="#ffffff" text-anchor="middle" dominant-baseline="central">%s</text>
|
||||
</svg>`
|
||||
|
||||
// GenerateSVGAvatar 根据用户名生成SVG头像
|
||||
// username: 用户名
|
||||
// size: 头像尺寸(像素)
|
||||
func GenerateSVGAvatar(username string, size int) string {
|
||||
initials := getInitials(username)
|
||||
color := stringToColor(username)
|
||||
return fmt.Sprintf(svgTemplate, size, size, color, initials)
|
||||
}
|
||||
|
||||
// GenerateAvatarDataURI 生成Data URI格式的头像
|
||||
// 可以直接在HTML img标签或CSS background-image中使用
|
||||
func GenerateAvatarDataURI(username string, size int) string {
|
||||
svg := GenerateSVGAvatar(username, size)
|
||||
encoded := base64.StdEncoding.EncodeToString([]byte(svg))
|
||||
return fmt.Sprintf("data:image/svg+xml;base64,%s", encoded)
|
||||
}
|
||||
|
||||
// getInitials 获取用户名首字母
|
||||
// 中文取第一个字,英文取首字母(最多2个)
|
||||
func getInitials(username string) string {
|
||||
if username == "" {
|
||||
return "?"
|
||||
}
|
||||
|
||||
// 检查是否是中文字符
|
||||
firstRune, _ := utf8.DecodeRuneInString(username)
|
||||
if isChinese(firstRune) {
|
||||
// 中文直接返回第一个字符
|
||||
return string(firstRune)
|
||||
}
|
||||
|
||||
// 英文处理:取前两个单词的首字母
|
||||
// 例如: "John Doe" -> "JD", "john" -> "J"
|
||||
result := []rune{}
|
||||
for i, r := range username {
|
||||
if i == 0 {
|
||||
result = append(result, toUpper(r))
|
||||
} else if r == ' ' || r == '_' || r == '-' {
|
||||
// 找到下一个字符作为第二个首字母
|
||||
nextIdx := i + 1
|
||||
if nextIdx < len(username) {
|
||||
nextRune, _ := utf8.DecodeRuneInString(username[nextIdx:])
|
||||
if nextRune != utf8.RuneError && nextRune != ' ' {
|
||||
result = append(result, toUpper(nextRune))
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(result) == 0 {
|
||||
return "?"
|
||||
}
|
||||
|
||||
// 最多返回2个字符
|
||||
if len(result) > 2 {
|
||||
result = result[:2]
|
||||
}
|
||||
|
||||
return string(result)
|
||||
}
|
||||
|
||||
// isChinese 判断是否是中文字符
|
||||
func isChinese(r rune) bool {
|
||||
return r >= 0x4E00 && r <= 0x9FFF
|
||||
}
|
||||
|
||||
// toUpper 将字母转换为大写
|
||||
func toUpper(r rune) rune {
|
||||
if r >= 'a' && r <= 'z' {
|
||||
return r - 32
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// stringToColor 根据字符串生成颜色
|
||||
// 使用简单的哈希算法确保同一用户名每次生成的颜色一致
|
||||
func stringToColor(s string) string {
|
||||
if s == "" {
|
||||
return colors[0]
|
||||
}
|
||||
|
||||
hash := 0
|
||||
for _, r := range s {
|
||||
hash = (hash*31 + int(r)) % len(colors)
|
||||
}
|
||||
if hash < 0 {
|
||||
hash = -hash
|
||||
}
|
||||
|
||||
return colors[hash%len(colors)]
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
package avatar
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGetInitials(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
username string
|
||||
want string
|
||||
}{
|
||||
{"中文用户名", "张三", "张"},
|
||||
{"英文用户名", "John", "J"},
|
||||
{"英文全名", "John Doe", "JD"},
|
||||
{"带下划线", "john_doe", "JD"},
|
||||
{"带连字符", "john-doe", "JD"},
|
||||
{"空字符串", "", "?"},
|
||||
{"小写英文", "alice", "A"},
|
||||
{"中文复合", "李小龙", "李"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := getInitials(tt.username)
|
||||
if got != tt.want {
|
||||
t.Errorf("getInitials(%q) = %q, want %q", tt.username, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStringToColor(t *testing.T) {
|
||||
// 测试同一用户名生成的颜色一致
|
||||
color1 := stringToColor("张三")
|
||||
color2 := stringToColor("张三")
|
||||
if color1 != color2 {
|
||||
t.Errorf("stringToColor should return consistent colors for the same input")
|
||||
}
|
||||
|
||||
// 测试不同用户名生成不同颜色(大概率)
|
||||
color3 := stringToColor("李四")
|
||||
if color1 == color3 {
|
||||
t.Logf("Warning: different usernames generated the same color (possible but unlikely)")
|
||||
}
|
||||
|
||||
// 测试空字符串
|
||||
color4 := stringToColor("")
|
||||
if color4 == "" {
|
||||
t.Errorf("stringToColor should return a color for empty string")
|
||||
}
|
||||
|
||||
// 验证颜色格式
|
||||
if !strings.HasPrefix(color4, "#") {
|
||||
t.Errorf("stringToColor should return hex color format starting with #")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateSVGAvatar(t *testing.T) {
|
||||
svg := GenerateSVGAvatar("张三", 100)
|
||||
|
||||
// 验证SVG结构
|
||||
if !strings.Contains(svg, "<svg") {
|
||||
t.Errorf("SVG should contain <svg tag")
|
||||
}
|
||||
if !strings.Contains(svg, "</svg>") {
|
||||
t.Errorf("SVG should contain </svg> tag")
|
||||
}
|
||||
if !strings.Contains(svg, "width=\"100\"") {
|
||||
t.Errorf("SVG should have width=100")
|
||||
}
|
||||
if !strings.Contains(svg, "height=\"100\"") {
|
||||
t.Errorf("SVG should have height=100")
|
||||
}
|
||||
if !strings.Contains(svg, "张") {
|
||||
t.Errorf("SVG should contain the initial character")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateAvatarDataURI(t *testing.T) {
|
||||
dataURI := GenerateAvatarDataURI("张三", 100)
|
||||
|
||||
// 验证Data URI格式
|
||||
if !strings.HasPrefix(dataURI, "data:image/svg+xml;base64,") {
|
||||
t.Errorf("Data URI should start with data:image/svg+xml;base64,")
|
||||
}
|
||||
|
||||
// 验证base64部分不为空
|
||||
parts := strings.Split(dataURI, ",")
|
||||
if len(parts) != 2 {
|
||||
t.Errorf("Data URI should have two parts separated by comma")
|
||||
}
|
||||
if parts[1] == "" {
|
||||
t.Errorf("Base64 part should not be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsChinese(t *testing.T) {
|
||||
tests := []struct {
|
||||
r rune
|
||||
want bool
|
||||
}{
|
||||
{'中', true},
|
||||
{'文', true},
|
||||
{'a', false},
|
||||
{'Z', false},
|
||||
{'0', false},
|
||||
{'_', false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := isChinese(tt.r)
|
||||
if got != tt.want {
|
||||
t.Errorf("isChinese(%q) = %v, want %v", tt.r, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,36 +21,6 @@ func BenchmarkEncryptDecryptSingle(b *testing.B) {
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkBatchDecrypt 批量并行解密性能基准
|
||||
func BenchmarkBatchDecrypt(b *testing.B) {
|
||||
key := "12345678901234567890123456789012"
|
||||
_ = InitMessageEncryptor(key, 1)
|
||||
encryptor := GetMessageEncryptor()
|
||||
|
||||
// 准备测试数据
|
||||
sizes := []int{10, 50, 100, 500}
|
||||
|
||||
for _, size := range sizes {
|
||||
b.Run(fmt.Sprintf("size_%d", size), func(b *testing.B) {
|
||||
// 生成加密数据
|
||||
ciphertexts := make([]string, size)
|
||||
for i := 0; i < size; i++ {
|
||||
msg := map[string]interface{}{
|
||||
"type": "text",
|
||||
"data": map[string]string{"content": fmt.Sprintf("消息内容 %d", i)},
|
||||
}
|
||||
plaintext, _ := json.Marshal(msg)
|
||||
ciphertexts[i], _ = encryptor.Encrypt(plaintext)
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = encryptor.BatchDecrypt(ciphertexts, 4)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkSerialDecrypt 串行解密性能基准(对比用)
|
||||
func BenchmarkSerialDecrypt(b *testing.B) {
|
||||
key := "12345678901234567890123456789012"
|
||||
@@ -81,12 +51,41 @@ func BenchmarkSerialDecrypt(b *testing.B) {
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkBatchDecrypt 批量并行解密性能基准
|
||||
func BenchmarkBatchDecrypt(b *testing.B) {
|
||||
key := "12345678901234567890123456789012"
|
||||
_ = InitMessageEncryptor(key, 1)
|
||||
encryptor := GetMessageEncryptor()
|
||||
|
||||
sizes := []int{10, 50, 100, 500}
|
||||
|
||||
for _, size := range sizes {
|
||||
b.Run(fmt.Sprintf("size_%d", size), func(b *testing.B) {
|
||||
// 生成加密数据
|
||||
ciphertexts := make([]string, size)
|
||||
for i := 0; i < size; i++ {
|
||||
msg := map[string]interface{}{
|
||||
"type": "text",
|
||||
"data": map[string]string{"content": fmt.Sprintf("消息内容 %d", i)},
|
||||
}
|
||||
plaintext, _ := json.Marshal(msg)
|
||||
ciphertexts[i], _ = encryptor.Encrypt(plaintext)
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = encryptor.BatchDecrypt(ciphertexts, 4)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBatchDecrypt 验证批量解密与单条解密结果一致
|
||||
func TestBatchDecrypt(t *testing.T) {
|
||||
key := "12345678901234567890123456789012"
|
||||
_ = InitMessageEncryptor(key, 1)
|
||||
encryptor := GetMessageEncryptor()
|
||||
|
||||
// 准备测试数据
|
||||
count := 100
|
||||
ciphertexts := make([]string, count)
|
||||
expectedContents := make([]string, count)
|
||||
@@ -105,6 +104,10 @@ func TestBatchDecrypt(t *testing.T) {
|
||||
// 批量解密
|
||||
results := encryptor.BatchDecrypt(ciphertexts, 4)
|
||||
|
||||
if len(results) != count {
|
||||
t.Fatalf("BatchDecrypt returned %d results, want %d", len(results), count)
|
||||
}
|
||||
|
||||
// 验证结果
|
||||
for i, result := range results {
|
||||
if result == nil {
|
||||
|
||||
@@ -139,31 +139,70 @@ func (e *MessageEncryptor) GetKeyVersion() int {
|
||||
return e.keyVersion
|
||||
}
|
||||
|
||||
// RotateKey 密钥轮换(用于密钥升级)
|
||||
// 新密钥必须也是32字节
|
||||
func (e *MessageEncryptor) RotateKey(newKey string, newVersion int) error {
|
||||
keyBytes := []byte(newKey)
|
||||
if len(keyBytes) != 32 {
|
||||
return ErrInvalidKey
|
||||
// BatchDecrypt 批量解密多条密文,返回与输入等长的明文字节切片数组。
|
||||
// 并发度由 workers 指定(<=0 时按密文数量自适应)。
|
||||
// 解密失败或空密文的位置返回 nil,调用方可据此判断。
|
||||
// 这是 Decrypt 的无锁读优化版:AEAD 的 Open 不修改内部状态,
|
||||
// 但仍走 RLock 以兼容未来可能的密钥轮换语义。
|
||||
func (e *MessageEncryptor) BatchDecrypt(ciphertexts []string, workers int) [][]byte {
|
||||
results := make([][]byte, len(ciphertexts))
|
||||
if e == nil || len(ciphertexts) == 0 {
|
||||
return results
|
||||
}
|
||||
|
||||
block, err := aes.NewCipher(keyBytes)
|
||||
if err != nil {
|
||||
return err
|
||||
// 自适应并发度:与历史实现保持一致
|
||||
if workers <= 0 {
|
||||
switch {
|
||||
case len(ciphertexts) < 20:
|
||||
workers = 2
|
||||
case len(ciphertexts) > 100:
|
||||
workers = 8
|
||||
default:
|
||||
workers = 4
|
||||
}
|
||||
}
|
||||
if workers > len(ciphertexts) {
|
||||
workers = len(ciphertexts)
|
||||
}
|
||||
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return err
|
||||
// 预取一次 AEAD,避免 worker 内重复进入 RLock
|
||||
e.mu.RLock()
|
||||
gcm := e.gcm
|
||||
nonceSize := e.gcm.NonceSize()
|
||||
e.mu.RUnlock()
|
||||
|
||||
jobs := make(chan int, len(ciphertexts))
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for w := 0; w < workers; w++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := range jobs {
|
||||
ct := ciphertexts[i]
|
||||
if ct == "" {
|
||||
continue
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(ct)
|
||||
if err != nil || len(raw) < nonceSize {
|
||||
continue
|
||||
}
|
||||
nonce := raw[:nonceSize]
|
||||
actual := raw[nonceSize:]
|
||||
plaintext, err := gcm.Open(nil, nonce, actual, nil)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
results[i] = plaintext
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
for i := range ciphertexts {
|
||||
jobs <- i
|
||||
}
|
||||
close(jobs)
|
||||
wg.Wait()
|
||||
|
||||
e.key = keyBytes
|
||||
e.gcm = gcm
|
||||
e.keyVersion = newVersion
|
||||
|
||||
return nil
|
||||
return results
|
||||
}
|
||||
|
||||
|
||||
@@ -150,16 +150,6 @@ func TestMessageEncryptor_KeyVersion(t *testing.T) {
|
||||
if encryptor.GetKeyVersion() != 1 {
|
||||
t.Errorf("GetKeyVersion() = %d, want 1", encryptor.GetKeyVersion())
|
||||
}
|
||||
|
||||
// 测试密钥轮换
|
||||
err = encryptor.RotateKey("abcdefghijklmnopqrstuvwxyz123456", 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if encryptor.GetKeyVersion() != 2 {
|
||||
t.Errorf("GetKeyVersion() after rotation = %d, want 2", encryptor.GetKeyVersion())
|
||||
}
|
||||
}
|
||||
|
||||
func mustMarshal(v interface{}) []byte {
|
||||
|
||||
Reference in New Issue
Block a user