feat(backend): 实现Go后端API并添加测试脚本
This commit is contained in:
8
background/apps.json
Normal file
8
background/apps.json
Normal file
@@ -0,0 +1,8 @@
|
||||
[
|
||||
{
|
||||
"id": "1766503652493156300",
|
||||
"name": "MobaXterm_Portable_v25.4",
|
||||
"fileName": "MobaXterm_Portable_v25.4.zip",
|
||||
"date": "2025-12-23 23:27:32"
|
||||
}
|
||||
]
|
||||
1
background/coverage
Normal file
1
background/coverage
Normal file
@@ -0,0 +1 @@
|
||||
mode: set
|
||||
BIN
background/files/b8bef48ec6f9c42a90f3843b076dcf80.zip
Normal file
BIN
background/files/b8bef48ec6f9c42a90f3843b076dcf80.zip
Normal file
Binary file not shown.
37
background/go.mod
Normal file
37
background/go.mod
Normal file
@@ -0,0 +1,37 @@
|
||||
module appdistribute
|
||||
|
||||
go 1.25
|
||||
|
||||
require (
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
github.com/stretchr/testify v1.8.3
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bytedance/sonic v1.9.1 // indirect
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.14.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
|
||||
github.com/leodido/go-urn v1.2.4 // indirect
|
||||
github.com/mattn/go-isatty v0.0.19 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.11 // indirect
|
||||
golang.org/x/arch v0.3.0 // indirect
|
||||
golang.org/x/crypto v0.9.0 // indirect
|
||||
golang.org/x/net v0.10.0 // indirect
|
||||
golang.org/x/sys v0.8.0 // indirect
|
||||
golang.org/x/text v0.9.0 // indirect
|
||||
google.golang.org/protobuf v1.30.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
86
background/go.sum
Normal file
86
background/go.sum
Normal file
@@ -0,0 +1,86 @@
|
||||
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
|
||||
github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
|
||||
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
|
||||
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=
|
||||
github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=
|
||||
github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
|
||||
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
|
||||
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
|
||||
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=
|
||||
github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=
|
||||
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
|
||||
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=
|
||||
golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/crypto v0.9.0 h1:LF6fAI+IutBocDJ2OT0Q1g8plpYljMZ4+lty+dsqw3g=
|
||||
golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0=
|
||||
golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
|
||||
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
233
background/main.go
Normal file
233
background/main.go
Normal file
@@ -0,0 +1,233 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// App 结构体定义
|
||||
type App struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
FileName string `json:"fileName"`
|
||||
Date string `json:"date"`
|
||||
FilePath string `json:"-"` // 内部使用,不序列化
|
||||
}
|
||||
|
||||
// 全局变量
|
||||
var (
|
||||
apps []App
|
||||
appsMutex sync.RWMutex // 读写锁,提高并发性能
|
||||
filesDir = "./files"
|
||||
jsonFile = "./apps.json"
|
||||
port = ":6902"
|
||||
)
|
||||
|
||||
// 生成唯一文件名
|
||||
func generateUniqueFileName(originalName string) string {
|
||||
// 获取文件扩展名
|
||||
ext := filepath.Ext(originalName)
|
||||
// 生成基于时间、随机数和原文件名的MD5哈希
|
||||
timestamp := time.Now().UnixNano()
|
||||
random := rand.Int63()
|
||||
hash := md5.Sum([]byte(fmt.Sprintf("%d%d%s", timestamp, random, originalName)))
|
||||
// 组合成新的唯一文件名
|
||||
return fmt.Sprintf("%s%s", hex.EncodeToString(hash[:]), ext)
|
||||
}
|
||||
|
||||
// 加载apps数据
|
||||
func loadApps() {
|
||||
appsMutex.Lock()
|
||||
defer appsMutex.Unlock()
|
||||
|
||||
file, err := os.Open(jsonFile)
|
||||
if err != nil {
|
||||
// 如果文件不存在,初始化空切片
|
||||
apps = []App{}
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
decoder := json.NewDecoder(file)
|
||||
if err := decoder.Decode(&apps); err != nil {
|
||||
apps = []App{}
|
||||
}
|
||||
}
|
||||
|
||||
// 保存apps数据
|
||||
func saveApps() error {
|
||||
appsMutex.RLock()
|
||||
defer appsMutex.RUnlock()
|
||||
|
||||
file, err := os.Create(jsonFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create apps.json: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
encoder := json.NewEncoder(file)
|
||||
encoder.SetIndent("", " ")
|
||||
if err := encoder.Encode(apps); err != nil {
|
||||
return fmt.Errorf("failed to encode apps: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
// 初始化随机数生成器
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
|
||||
// 创建files目录
|
||||
if err := os.MkdirAll(filesDir, 0755); err != nil {
|
||||
panic(fmt.Sprintf("failed to create files directory: %v", err))
|
||||
}
|
||||
|
||||
// 加载apps数据
|
||||
loadApps()
|
||||
|
||||
// 创建Gin引擎
|
||||
// 生产环境中应该使用gin.ReleaseMode
|
||||
// gin.SetMode(gin.ReleaseMode)
|
||||
r := gin.Default()
|
||||
|
||||
// 添加CORS中间件
|
||||
r.Use(func(c *gin.Context) {
|
||||
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
|
||||
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(204)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
})
|
||||
|
||||
// API路由
|
||||
api := r.Group("/api")
|
||||
{
|
||||
api.GET("/apps", getApps)
|
||||
api.POST("/apps", uploadApp)
|
||||
api.GET("/apps/:id", downloadApp)
|
||||
}
|
||||
|
||||
// 启动服务器
|
||||
fmt.Printf("Server is running on http://localhost%s\n", port)
|
||||
if err := r.Run(port); err != nil {
|
||||
panic(fmt.Sprintf("failed to start server: %v", err))
|
||||
}
|
||||
}
|
||||
|
||||
// 获取App列表
|
||||
func getApps(c *gin.Context) {
|
||||
appsMutex.RLock()
|
||||
defer appsMutex.RUnlock()
|
||||
|
||||
c.JSON(http.StatusOK, apps)
|
||||
}
|
||||
|
||||
// 上传App
|
||||
func uploadApp(c *gin.Context) {
|
||||
// 获取表单数据
|
||||
name := c.PostForm("name")
|
||||
if name == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "App名称不能为空"})
|
||||
return
|
||||
}
|
||||
|
||||
// 获取上传的文件
|
||||
file, header, err := c.Request.FormFile("file")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"success": false, "message": "文件上传失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 生成唯一ID和文件名
|
||||
id := fmt.Sprintf("%d", time.Now().UnixNano())
|
||||
originalFileName := header.Filename
|
||||
uniqueFileName := generateUniqueFileName(originalFileName)
|
||||
filePath := filepath.Join(filesDir, uniqueFileName)
|
||||
|
||||
// 创建目标文件
|
||||
dst, err := os.Create(filePath)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "文件保存失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
defer dst.Close()
|
||||
|
||||
// 复制文件内容
|
||||
if _, err = io.Copy(dst, file); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "文件复制失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// 添加到App列表
|
||||
newApp := App{
|
||||
ID: id,
|
||||
Name: name,
|
||||
FileName: originalFileName,
|
||||
FilePath: uniqueFileName,
|
||||
Date: time.Now().Format("2006-01-02 15:04:05"),
|
||||
}
|
||||
|
||||
appsMutex.Lock()
|
||||
apps = append(apps, newApp)
|
||||
appsMutex.Unlock()
|
||||
|
||||
// 保存到文件
|
||||
if err := saveApps(); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "保存数据失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
|
||||
// 下载指定App
|
||||
func downloadApp(c *gin.Context) {
|
||||
// 获取ID
|
||||
id := c.Param("id")
|
||||
|
||||
// 查找App
|
||||
appsMutex.RLock()
|
||||
var targetApp *App
|
||||
for i := range apps {
|
||||
if apps[i].ID == id {
|
||||
targetApp = &apps[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
appsMutex.RUnlock()
|
||||
|
||||
if targetApp == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"success": false, "message": "App不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
// 构建文件路径
|
||||
filePath := filepath.Join(filesDir, targetApp.FilePath)
|
||||
|
||||
// 检查文件是否存在
|
||||
if _, err := os.Stat(filePath); os.IsNotExist(err) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"success": false, "message": "文件不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
// 提供文件下载,设置原始文件名
|
||||
c.FileAttachment(filePath, targetApp.FileName)
|
||||
}
|
||||
166
background/test_scripts/concurrent_load.go
Normal file
166
background/test_scripts/concurrent_load.go
Normal file
@@ -0,0 +1,166 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
baseURL = "http://localhost:6902/api"
|
||||
concurrency = 10 // 并发数
|
||||
)
|
||||
|
||||
// 并发上传文件
|
||||
func concurrentUploads(wg *sync.WaitGroup, filePaths []string, results chan<- string) {
|
||||
defer wg.Done()
|
||||
|
||||
for _, filePath := range filePaths {
|
||||
// 打开文件
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error opening file %s: %v", filePath, err)
|
||||
continue
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 创建multipart表单
|
||||
body := &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(body)
|
||||
|
||||
// 添加name字段
|
||||
appName := filepath.Base(filePath)
|
||||
writer.WriteField("name", appName)
|
||||
|
||||
// 添加file字段
|
||||
part, err := writer.CreateFormFile("file", filepath.Base(filePath))
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error creating form file %s: %v", filePath, err)
|
||||
continue
|
||||
}
|
||||
|
||||
// 复制文件内容
|
||||
_, err = io.Copy(part, file)
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error copying file content %s: %v", filePath, err)
|
||||
continue
|
||||
}
|
||||
|
||||
writer.Close()
|
||||
|
||||
// 创建请求
|
||||
req, err := http.NewRequest("POST", baseURL+"/apps", body)
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error creating request for %s: %v", filePath, err)
|
||||
continue
|
||||
}
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
// 发送请求
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error sending request for %s: %v", filePath, err)
|
||||
continue
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
results <- fmt.Sprintf("Successfully uploaded %s", filePath)
|
||||
} else {
|
||||
results <- fmt.Sprintf("Failed to upload %s, status: %d", filePath, resp.StatusCode)
|
||||
}
|
||||
|
||||
// 等待一下,避免请求过于密集
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// 并发获取App列表
|
||||
func concurrentGetApps(wg *sync.WaitGroup, results chan<- string) {
|
||||
defer wg.Done()
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
resp, err := http.Get(baseURL + "/apps")
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error getting apps: %v", err)
|
||||
continue
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
results <- "Successfully got apps list"
|
||||
} else {
|
||||
results <- fmt.Sprintf("Failed to get apps list, status: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// 等待一下,避免请求过于密集
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println("Starting concurrent test...")
|
||||
startTime := time.Now()
|
||||
|
||||
// 获取测试文件列表
|
||||
testFiles := []string{
|
||||
"fake_files/empty.txt",
|
||||
"fake_files/fake_file_0_4.txt",
|
||||
}
|
||||
|
||||
// 创建结果通道
|
||||
results := make(chan string, 100)
|
||||
|
||||
// 创建WaitGroup
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// 启动并发上传协程
|
||||
for i := 0; i < concurrency; i++ {
|
||||
wg.Add(1)
|
||||
go concurrentUploads(&wg, testFiles, results)
|
||||
}
|
||||
|
||||
// 启动并发获取App列表协程
|
||||
for i := 0; i < concurrency/2; i++ {
|
||||
wg.Add(1)
|
||||
go concurrentGetApps(&wg, results)
|
||||
}
|
||||
|
||||
// 等待所有协程完成
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
// 打印结果
|
||||
fmt.Println("\nTest Results:")
|
||||
successCount := 0
|
||||
errorCount := 0
|
||||
for result := range results {
|
||||
fmt.Println(result)
|
||||
if len(result) > 8 && result[:8] == "Successfully" {
|
||||
successCount++
|
||||
} else {
|
||||
errorCount++
|
||||
}
|
||||
}
|
||||
|
||||
// 打印统计信息
|
||||
totalTime := time.Since(startTime)
|
||||
fmt.Printf("\nTest Statistics:")
|
||||
fmt.Printf("\n- Total requests: %d", successCount+errorCount)
|
||||
fmt.Printf("\n- Successful requests: %d", successCount)
|
||||
fmt.Printf("\n- Failed requests: %d", errorCount)
|
||||
fmt.Printf("\n- Total time: %v", totalTime)
|
||||
fmt.Printf("\n- Requests per second: %.2f\n", float64(successCount+errorCount)/totalTime.Seconds())
|
||||
|
||||
if errorCount == 0 {
|
||||
fmt.Println("\n✅ All concurrent requests succeeded! System is stable.")
|
||||
} else {
|
||||
fmt.Printf("\n❌ %d concurrent requests failed. System may have stability issues.", errorCount)
|
||||
}
|
||||
}
|
||||
166
background/test_scripts/concurrent_load_test.go
Normal file
166
background/test_scripts/concurrent_load_test.go
Normal file
@@ -0,0 +1,166 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
baseURL = "http://localhost:6902/api"
|
||||
concurrency = 10 // 并发数
|
||||
)
|
||||
|
||||
// 并发上传文件
|
||||
func concurrentUploads(wg *sync.WaitGroup, filePaths []string, results chan<- string) {
|
||||
defer wg.Done()
|
||||
|
||||
for _, filePath := range filePaths {
|
||||
// 打开文件
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error opening file %s: %v", filePath, err)
|
||||
continue
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 创建multipart表单
|
||||
body := &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(body)
|
||||
|
||||
// 添加name字段
|
||||
appName := filepath.Base(filePath)
|
||||
writer.WriteField("name", appName)
|
||||
|
||||
// 添加file字段
|
||||
part, err := writer.CreateFormFile("file", filepath.Base(filePath))
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error creating form file %s: %v", filePath, err)
|
||||
continue
|
||||
}
|
||||
|
||||
// 复制文件内容
|
||||
_, err = io.Copy(part, file)
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error copying file content %s: %v", filePath, err)
|
||||
continue
|
||||
}
|
||||
|
||||
writer.Close()
|
||||
|
||||
// 创建请求
|
||||
req, err := http.NewRequest("POST", baseURL+"/apps", body)
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error creating request for %s: %v", filePath, err)
|
||||
continue
|
||||
}
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
// 发送请求
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error sending request for %s: %v", filePath, err)
|
||||
continue
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
results <- fmt.Sprintf("Successfully uploaded %s", filePath)
|
||||
} else {
|
||||
results <- fmt.Sprintf("Failed to upload %s, status: %d", filePath, resp.StatusCode)
|
||||
}
|
||||
|
||||
// 等待一下,避免请求过于密集
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// 并发获取App列表
|
||||
func concurrentGetApps(wg *sync.WaitGroup, results chan<- string) {
|
||||
defer wg.Done()
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
resp, err := http.Get(baseURL + "/apps")
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error getting apps: %v", err)
|
||||
continue
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
results <- "Successfully got apps list"
|
||||
} else {
|
||||
results <- fmt.Sprintf("Failed to get apps list, status: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// 等待一下,避免请求过于密集
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println("Starting concurrent test...")
|
||||
startTime := time.Now()
|
||||
|
||||
// 获取测试文件列表
|
||||
testFiles := []string{
|
||||
"fake_files/empty.txt",
|
||||
"fake_files/fake_file_0_4.txt",
|
||||
}
|
||||
|
||||
// 创建结果通道
|
||||
results := make(chan string, 100)
|
||||
|
||||
// 创建WaitGroup
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// 启动并发上传协程
|
||||
for i := 0; i < concurrency; i++ {
|
||||
wg.Add(1)
|
||||
go concurrentUploads(&wg, testFiles, results)
|
||||
}
|
||||
|
||||
// 启动并发获取App列表协程
|
||||
for i := 0; i < concurrency/2; i++ {
|
||||
wg.Add(1)
|
||||
go concurrentGetApps(&wg, results)
|
||||
}
|
||||
|
||||
// 等待所有协程完成
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
// 打印结果
|
||||
fmt.Println("\nTest Results:")
|
||||
successCount := 0
|
||||
errorCount := 0
|
||||
for result := range results {
|
||||
fmt.Println(result)
|
||||
if len(result) > 8 && result[:8] == "Successfully" {
|
||||
successCount++
|
||||
} else {
|
||||
errorCount++
|
||||
}
|
||||
}
|
||||
|
||||
// 打印统计信息
|
||||
totalTime := time.Since(startTime)
|
||||
fmt.Printf("\nTest Statistics:")
|
||||
fmt.Printf("\n- Total requests: %d", successCount+errorCount)
|
||||
fmt.Printf("\n- Successful requests: %d", successCount)
|
||||
fmt.Printf("\n- Failed requests: %d", errorCount)
|
||||
fmt.Printf("\n- Total time: %v", totalTime)
|
||||
fmt.Printf("\n- Requests per second: %.2f\n", float64(successCount+errorCount)/totalTime.Seconds())
|
||||
|
||||
if errorCount == 0 {
|
||||
fmt.Println("\n✅ All concurrent requests succeeded! System is stable.")
|
||||
} else {
|
||||
fmt.Printf("\n❌ %d concurrent requests failed. System may have stability issues.", errorCount)
|
||||
}
|
||||
}
|
||||
166
background/test_scripts/concurrent_test.go
Normal file
166
background/test_scripts/concurrent_test.go
Normal file
@@ -0,0 +1,166 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
baseURL = "http://localhost:6902/api"
|
||||
concurrency = 10 // 并发数
|
||||
)
|
||||
|
||||
// 并发上传文件
|
||||
func concurrentUploads(wg *sync.WaitGroup, filePaths []string, results chan<- string) {
|
||||
defer wg.Done()
|
||||
|
||||
for _, filePath := range filePaths {
|
||||
// 打开文件
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error opening file %s: %v", filePath, err)
|
||||
continue
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 创建multipart表单
|
||||
body := &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(body)
|
||||
|
||||
// 添加name字段
|
||||
appName := filepath.Base(filePath)
|
||||
writer.WriteField("name", appName)
|
||||
|
||||
// 添加file字段
|
||||
part, err := writer.CreateFormFile("file", filepath.Base(filePath))
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error creating form file %s: %v", filePath, err)
|
||||
continue
|
||||
}
|
||||
|
||||
// 复制文件内容
|
||||
_, err = io.Copy(part, file)
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error copying file content %s: %v", filePath, err)
|
||||
continue
|
||||
}
|
||||
|
||||
writer.Close()
|
||||
|
||||
// 创建请求
|
||||
req, err := http.NewRequest("POST", baseURL+"/apps", body)
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error creating request for %s: %v", filePath, err)
|
||||
continue
|
||||
}
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
// 发送请求
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error sending request for %s: %v", filePath, err)
|
||||
continue
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
results <- fmt.Sprintf("Successfully uploaded %s", filePath)
|
||||
} else {
|
||||
results <- fmt.Sprintf("Failed to upload %s, status: %d", filePath, resp.StatusCode)
|
||||
}
|
||||
|
||||
// 等待一下,避免请求过于密集
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// 并发获取App列表
|
||||
func concurrentGetApps(wg *sync.WaitGroup, results chan<- string) {
|
||||
defer wg.Done()
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
resp, err := http.Get(baseURL + "/apps")
|
||||
if err != nil {
|
||||
results <- fmt.Sprintf("Error getting apps: %v", err)
|
||||
continue
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
results <- "Successfully got apps list"
|
||||
} else {
|
||||
results <- fmt.Sprintf("Failed to get apps list, status: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// 等待一下,避免请求过于密集
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println("Starting concurrent test...")
|
||||
startTime := time.Now()
|
||||
|
||||
// 获取测试文件列表
|
||||
testFiles := []string{
|
||||
"fake_files/empty.txt",
|
||||
"fake_files/fake_file_0_4.txt",
|
||||
}
|
||||
|
||||
// 创建结果通道
|
||||
results := make(chan string, 100)
|
||||
|
||||
// 创建WaitGroup
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// 启动并发上传协程
|
||||
for i := 0; i < concurrency; i++ {
|
||||
wg.Add(1)
|
||||
go concurrentUploads(&wg, testFiles, results)
|
||||
}
|
||||
|
||||
// 启动并发获取App列表协程
|
||||
for i := 0; i < concurrency/2; i++ {
|
||||
wg.Add(1)
|
||||
go concurrentGetApps(&wg, results)
|
||||
}
|
||||
|
||||
// 等待所有协程完成
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
// 打印结果
|
||||
fmt.Println("\nTest Results:")
|
||||
successCount := 0
|
||||
errorCount := 0
|
||||
for result := range results {
|
||||
fmt.Println(result)
|
||||
if len(result) > 8 && result[:8] == "Successfully" {
|
||||
successCount++
|
||||
} else {
|
||||
errorCount++
|
||||
}
|
||||
}
|
||||
|
||||
// 打印统计信息
|
||||
totalTime := time.Since(startTime)
|
||||
fmt.Printf("\nTest Statistics:")
|
||||
fmt.Printf("\n- Total requests: %d", successCount+errorCount)
|
||||
fmt.Printf("\n- Successful requests: %d", successCount)
|
||||
fmt.Printf("\n- Failed requests: %d", errorCount)
|
||||
fmt.Printf("\n- Total time: %v", totalTime)
|
||||
fmt.Printf("\n- Requests per second: %.2f\n", float64(successCount+errorCount)/totalTime.Seconds())
|
||||
|
||||
if errorCount == 0 {
|
||||
fmt.Println("\n✅ All concurrent requests succeeded! System is stable.")
|
||||
} else {
|
||||
fmt.Printf("\n❌ %d concurrent requests failed. System may have stability issues.", errorCount)
|
||||
}
|
||||
}
|
||||
68
background/test_scripts/generate_fake_files.go
Normal file
68
background/test_scripts/generate_fake_files.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 生成指定大小的随机字节数据
|
||||
func generateRandomData(size int64) []byte {
|
||||
data := make([]byte, size)
|
||||
_, err := rand.Read(data)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// 生成假文件
|
||||
func generateFakeFiles() {
|
||||
// 确保输出目录存在
|
||||
outputDir := "fake_files"
|
||||
err := os.MkdirAll(outputDir, 0755)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// 定义要生成的文件类型和大小
|
||||
fileTypes := []string{".apk", ".ipa", ".zip", ".txt", ".pdf"}
|
||||
fileSizes := []int64{
|
||||
1024, // 1KB
|
||||
1024 * 1024, // 1MB
|
||||
5 * 1024 * 1024, // 5MB
|
||||
}
|
||||
|
||||
// 生成文件
|
||||
for i, size := range fileSizes {
|
||||
for _, ext := range fileTypes {
|
||||
filename := fmt.Sprintf("fake_file_%d_%d%s", i, len(ext), ext)
|
||||
filepath := filepath.Join(outputDir, filename)
|
||||
data := generateRandomData(size)
|
||||
err := os.WriteFile(filepath, data, 0644)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf("Generated %s (%d bytes)\n", filepath, size)
|
||||
}
|
||||
}
|
||||
|
||||
// 生成一个空文件
|
||||
emptyFile := filepath.Join(outputDir, "empty.txt")
|
||||
err = os.WriteFile(emptyFile, []byte{}, 0644)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf("Generated %s (0 bytes)\n", emptyFile)
|
||||
}
|
||||
|
||||
func main() {
|
||||
// 初始化随机数生成器
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
|
||||
fmt.Println("Generating fake files...")
|
||||
generateFakeFiles()
|
||||
fmt.Println("Fake files generated successfully!")
|
||||
}
|
||||
252
background/test_scripts/test_backend.go
Normal file
252
background/test_scripts/test_backend.go
Normal file
@@ -0,0 +1,252 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
baseURL = "http://localhost:6902/api"
|
||||
)
|
||||
|
||||
// App 结构体定义
|
||||
type App struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
FileName string `json:"fileName"`
|
||||
Date string `json:"date"`
|
||||
}
|
||||
|
||||
// 获取App列表
|
||||
func getApps() ([]App, error) {
|
||||
resp, err := http.Get(baseURL + "/apps")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var apps []App
|
||||
if err := json.Unmarshal(body, &apps); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return apps, nil
|
||||
}
|
||||
|
||||
// 上传App
|
||||
func uploadApp(name, filePath string) (bool, error) {
|
||||
// 打开文件
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 创建multipart表单
|
||||
body := &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(body)
|
||||
|
||||
// 添加name字段
|
||||
writer.WriteField("name", name)
|
||||
|
||||
// 添加file字段
|
||||
part, err := writer.CreateFormFile("file", filepath.Base(filePath))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// 复制文件内容到表单
|
||||
if _, err := io.Copy(part, file); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
writer.Close()
|
||||
|
||||
// 创建请求
|
||||
req, err := http.NewRequest("POST", baseURL+"/apps", body)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
// 发送请求
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// 解析响应
|
||||
respBody, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
var response map[string]bool
|
||||
if err := json.Unmarshal(respBody, &response); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return response["success"], nil
|
||||
}
|
||||
|
||||
// 下载App
|
||||
func downloadApp(id string) ([]byte, error) {
|
||||
resp, err := http.Get(baseURL + "/apps/" + id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := ioutil.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("download failed: %s, %s", resp.Status, string(body))
|
||||
}
|
||||
|
||||
return ioutil.ReadAll(resp.Body)
|
||||
}
|
||||
|
||||
// 测试上传和下载功能
|
||||
func testUploadDownload() error {
|
||||
// 获取当前目录下的fake_files目录
|
||||
fakeFilesDir := "fake_files"
|
||||
|
||||
// 读取fake_files目录下的所有文件
|
||||
files, err := ioutil.ReadDir(fakeFilesDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 上传每个文件
|
||||
for _, file := range files {
|
||||
if file.IsDir() {
|
||||
continue
|
||||
}
|
||||
|
||||
filePath := filepath.Join(fakeFilesDir, file.Name())
|
||||
appName := strings.TrimSuffix(file.Name(), filepath.Ext(file.Name()))
|
||||
|
||||
fmt.Printf("Uploading %s...\n", file.Name())
|
||||
success, err := uploadApp(appName, filePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to upload %s: %v", file.Name(), err)
|
||||
}
|
||||
if !success {
|
||||
return fmt.Errorf("upload %s failed", file.Name())
|
||||
}
|
||||
fmt.Printf("Uploaded %s successfully\n", file.Name())
|
||||
|
||||
// 等待一下,避免并发问题
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
|
||||
// 获取App列表
|
||||
apps, err := getApps()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get apps: %v", err)
|
||||
}
|
||||
|
||||
fmt.Printf("\nTotal %d apps uploaded:\n", len(apps))
|
||||
for _, app := range apps {
|
||||
fmt.Printf("- %s (%s)\n", app.Name, app.FileName)
|
||||
}
|
||||
|
||||
// 测试下载第一个App
|
||||
if len(apps) > 0 {
|
||||
fmt.Printf("\nDownloading %s...\n", apps[0].FileName)
|
||||
data, err := downloadApp(apps[0].ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to download %s: %v", apps[0].FileName, err)
|
||||
}
|
||||
fmt.Printf("Downloaded %s successfully, size: %d bytes\n", apps[0].FileName, len(data))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// 测试文件覆盖情况
|
||||
func testFileOverwrite() error {
|
||||
// 上传同一个文件两次,测试是否会覆盖
|
||||
filePath := "fake_files/empty.txt"
|
||||
appName := "Test Overwrite"
|
||||
|
||||
fmt.Printf("\nTesting file overwrite...\n")
|
||||
|
||||
// 第一次上传
|
||||
fmt.Printf("First upload of %s...\n", filePath)
|
||||
success, err := uploadApp(appName, filePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("first upload failed: %v", err)
|
||||
}
|
||||
if !success {
|
||||
return fmt.Errorf("first upload returned false")
|
||||
}
|
||||
|
||||
// 第二次上传
|
||||
fmt.Printf("Second upload of %s...\n", filePath)
|
||||
success, err = uploadApp(appName+" 2", filePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("second upload failed: %v", err)
|
||||
}
|
||||
if !success {
|
||||
return fmt.Errorf("second upload returned false")
|
||||
}
|
||||
|
||||
// 获取App列表,应该有两个不同ID的App,但文件名相同
|
||||
apps, err := getApps()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get apps: %v", err)
|
||||
}
|
||||
|
||||
fmt.Printf("\nAfter two uploads, total %d apps:\n", len(apps))
|
||||
emptyTxtApps := 0
|
||||
for _, app := range apps {
|
||||
if app.FileName == "empty.txt" {
|
||||
emptyTxtApps++
|
||||
fmt.Printf("- %s (%s) [ID: %s]\n", app.Name, app.FileName, app.ID)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Printf("\nFound %d apps with filename 'empty.txt'\n", emptyTxtApps)
|
||||
if emptyTxtApps != 2 {
|
||||
return fmt.Errorf("expected 2 apps with filename 'empty.txt', got %d", emptyTxtApps)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println("Testing app distribution backend...")
|
||||
|
||||
// 等待服务启动
|
||||
fmt.Println("\nWaiting for server to start...")
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
// 测试上传下载功能
|
||||
if err := testUploadDownload(); err != nil {
|
||||
fmt.Printf("Error in testUploadDownload: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 测试文件覆盖情况
|
||||
if err := testFileOverwrite(); err != nil {
|
||||
fmt.Printf("Error in testFileOverwrite: %v\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("\nAll tests passed successfully!")
|
||||
}
|
||||
Reference in New Issue
Block a user