61 lines
1.4 KiB
Go
61 lines
1.4 KiB
Go
package api
|
|
|
|
import (
|
|
"ZhenTuLocalPassiveAdapter/config"
|
|
"ZhenTuLocalPassiveAdapter/dto"
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
func SyncTask() ([]dto.Task, error) {
|
|
url := config.Config.Api.BaseUrl + "/sync"
|
|
requestBody := map[string]interface{}{
|
|
"version": "0.0.1",
|
|
"devices": config.Config.Devices,
|
|
}
|
|
jsonData, err := json.Marshal(requestBody)
|
|
if err != nil {
|
|
log.Println("Error marshaling JSON:", err)
|
|
return nil, err
|
|
}
|
|
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
|
|
if err != nil {
|
|
log.Println("Error creating request:", err)
|
|
return nil, err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
client := &http.Client{
|
|
Timeout: 5 * time.Second, // 设置超时时间为5秒
|
|
}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
log.Println("Error sending request:", err)
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
log.Println("Error reading response body:", err)
|
|
return nil, err
|
|
}
|
|
|
|
// 解析响应体为 map
|
|
var response dto.TaskListResponse
|
|
err = json.Unmarshal(body, &response)
|
|
if err != nil {
|
|
log.Println("->:", string(body))
|
|
log.Println("Error unmarshaling response body:", err)
|
|
return nil, err
|
|
}
|
|
if response.Code != 200 {
|
|
log.Println("Error response code:", response.Code)
|
|
return nil, fmt.Errorf(response.Msg)
|
|
}
|
|
return response.Data, nil
|
|
}
|