新增保存Json数据到文件

This commit is contained in:
aixiao 2025-01-07 18:04:13 +08:00
parent e28e66ffb3
commit d74d5d1248
2 changed files with 32 additions and 0 deletions

32
curl.go
View File

@ -7,6 +7,7 @@ import (
"log" "log"
"net" "net"
"net/http" "net/http"
"os"
"time" "time"
) )
@ -34,6 +35,32 @@ func isValidIP(ip string) bool {
return net.ParseIP(ip) != nil return net.ParseIP(ip) != nil
} }
func SaveBytesToFile(data []byte, filename string, syncToDisk bool) error {
if filename == "" {
return fmt.Errorf("filename cannot be empty")
}
file, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return fmt.Errorf("failed to open file %q: %w", filename, err)
}
defer file.Close()
_, err = file.Write(data)
if err != nil {
return fmt.Errorf("failed to write to file %q: %w", filename, err)
}
if syncToDisk {
err = file.Sync()
if err != nil {
return fmt.Errorf("failed to sync data to disk for file %q: %w", filename, err)
}
}
return nil
}
func curl_(IP_ADDR string) (string, error) { func curl_(IP_ADDR string) (string, error) {
var ( var (
err error err error
@ -98,6 +125,11 @@ func curl_(IP_ADDR string) (string, error) {
log.Printf("读取响应体时出错: %v", err) log.Printf("读取响应体时出错: %v", err)
} }
// 保存响应体到文件
if err := SaveBytesToFile(append(HTTP_BODY, '\n'), "response.json", true); err != nil {
log.Printf("failed to save HTTP response to file: %v", err)
}
// 解析 JSON 数据 // 解析 JSON 数据
err = json.Unmarshal(HTTP_BODY, &HTPP_JSON) err = json.Unmarshal(HTTP_BODY, &HTPP_JSON)
if err != nil { if err != nil {

BIN
denyip

Binary file not shown.