- 在 UploadDataToServer 函数中添加 context 参数支持 - 使用 http.NewRequest 替换 httpClient.Post 以更好地控制请求上下文 - 重构应用启动逻辑,在 StartUpload 中初始化上传器上下文 - 优化 StopUpload 方法中的上下文取消机制 - 移除上传过程中的 wg.Wait() 调用以改善并发性能
This commit is contained in:
@@ -65,12 +65,12 @@ func (a *App) StartUpload() {
|
||||
if isRun {
|
||||
return
|
||||
}
|
||||
a.uploaderCTX, a.uploaderCancel = context.WithCancel(a.ctx)
|
||||
go uploader.StartLooking(a.uploaderCTX, &a.logChan, config.APPConfig.CheckDir)
|
||||
}
|
||||
|
||||
func (a *App) StopUpload() {
|
||||
if isRun {
|
||||
a.uploaderCancel()
|
||||
a.uploaderCTX, a.uploaderCancel = context.WithCancel(a.ctx)
|
||||
}
|
||||
}
|
||||
|
||||
+12
-3
@@ -1,6 +1,7 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"dypid-client/internal/config"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -17,18 +18,26 @@ var httpClient = &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
}
|
||||
|
||||
func UploadDataToServer(data string) error {
|
||||
func UploadDataToServer(ctx context.Context, data string) error {
|
||||
params := url.Values{}
|
||||
params.Set("token", config.APPConfig.Token)
|
||||
params.Set("data", data)
|
||||
|
||||
//http://127.0.0.1:8080/api/data?token=123456&data=123456
|
||||
resp, err := httpClient.Post(config.APPConfig.Url+"/api/data?"+params.Encode(),
|
||||
"", nil,
|
||||
request, err := http.NewRequest(
|
||||
"POST",
|
||||
config.APPConfig.Url+"/api/data?"+params.Encode(),
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
request.WithContext(ctx)
|
||||
|
||||
resp, err := httpClient.Do(request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp != nil {
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
resp.Body.Close()
|
||||
|
||||
@@ -211,7 +211,6 @@ func processFile(ctx context.Context, logChan *chan string, filePath string, fil
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
close(lines)
|
||||
wg.Wait()
|
||||
return
|
||||
default:
|
||||
progress.Store(filepath.Base(filePath),
|
||||
@@ -245,7 +244,7 @@ func processLines(ctx context.Context, logChan *chan string, lines *chan string,
|
||||
continue
|
||||
}
|
||||
// 上传数据
|
||||
if err := api.UploadDataToServer(line); err != nil {
|
||||
if err := api.UploadDataToServer(ctx, line); err != nil {
|
||||
AddLog(logChan, fmt.Sprintf("Worker %d (文件 %s): 上传失败: %v", workerID, filePath, err))
|
||||
}
|
||||
atomic.AddInt32(countLine, 1)
|
||||
|
||||
Reference in New Issue
Block a user