Skip to content

Commit 919e19d

Browse files
feat: add ToFile support to write the response into a file
1 parent c494153 commit 919e19d

File tree

2 files changed

+114
-0
lines changed

2 files changed

+114
-0
lines changed

huaweicloud/helper/httphelper/http_helper.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,21 @@ import (
55
"encoding/json"
66
"fmt"
77
"io"
8+
"log"
89
"net/url"
910
"reflect"
1011
"strconv"
1112
"strings"
1213

14+
"github.com/hashicorp/go-multierror"
1315
"github.com/hashicorp/go-uuid"
1416
"github.com/tidwall/gjson"
1517

1618
"github.com/chnsz/golangsdk"
1719
"github.com/chnsz/golangsdk/pagination"
1820

1921
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/helper/filters"
22+
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils"
2023
)
2124

2225
type HttpHelper struct {
@@ -265,6 +268,55 @@ func (c *HttpHelper) ExtractInto(to any) error {
265268
return json.Unmarshal(c.responseBody, to)
266269
}
267270

271+
func (c *HttpHelper) ToFile(dataPath, filePath string) error {
272+
err := utils.WriteToFile(filePath, "", false)
273+
if err != nil {
274+
return err
275+
}
276+
277+
var fileErr error
278+
count := 0
279+
err = c.EachPage(func(jsonData *gjson.Result, err error) bool {
280+
arr := jsonData.Get(dataPath).Array()
281+
for _, v := range arr {
282+
if err := utils.WriteToFile(filePath, fmt.Sprintf("%s\n", v.Raw), true); err != nil {
283+
log.Printf("[ERROR] unable to write file: %s, error: %s", filePath, err)
284+
count++
285+
fileErr = fmt.Errorf("%v items that failed to be written to the file %s", count, err)
286+
}
287+
}
288+
return true
289+
})
290+
291+
mErr := multierror.Append(nil, err, fileErr)
292+
return mErr.ErrorOrNil()
293+
}
294+
295+
func (c *HttpHelper) EachPage(handler func(*gjson.Result, error) bool) error {
296+
if c.method == "" {
297+
c.result.Err = fmt.Errorf("`method` is empty, please specify the client through Client(method string)")
298+
}
299+
if c.result.Err != nil {
300+
return c.result.Err
301+
}
302+
303+
if c.pager == nil {
304+
return fmt.Errorf("`EachPage` only supports paginated query data")
305+
}
306+
307+
c.buildURL()
308+
c.appendQueryParams()
309+
310+
pager := pagination.NewPager(c.client, c.url, c.pager)
311+
pager.Headers = c.requestOpts.MoreHeaders
312+
313+
return pager.EachPage(func(page pagination.Page) (bool, error) {
314+
jsonData, err := bodyToGJson(page.GetBody())
315+
b := handler(jsonData, err)
316+
return b, nil
317+
})
318+
}
319+
268320
func (c *HttpHelper) requestWithPage() {
269321
body := make(map[string]any)
270322
pager := pagination.NewPager(c.client, c.url, c.pager)

huaweicloud/utils/utils.go

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -556,3 +556,65 @@ func IsUUID(uuid string) bool {
556556
match, _ := regexp.MatchString(pattern, uuid)
557557
return match
558558
}
559+
560+
func mkdirParentDir(filePath string) error {
561+
// 替换路径中的反斜杠为正斜杠,确保路径在不同操作系统中的兼容性
562+
filePath = strings.ReplaceAll(filePath, "\\", "/")
563+
564+
// 获取目录路径
565+
pos := strings.LastIndexByte(filePath, '/')
566+
if pos == -1 {
567+
return nil
568+
}
569+
directory := filePath[:pos]
570+
571+
if err := os.MkdirAll(directory, os.ModePerm); err != nil && !os.IsExist(err) {
572+
return fmt.Errorf("failed to create directory: %s, error: %s", directory, err)
573+
}
574+
return nil
575+
}
576+
577+
func WriteToFile(path, content string, append bool) error {
578+
if err := mkdirParentDir(path); err != nil {
579+
return err
580+
}
581+
582+
_, err := os.Stat(path)
583+
if os.IsNotExist(err) {
584+
file, err := os.Create(path)
585+
if err != nil {
586+
return fmt.Errorf("[ERROR] failed to create file: %s, error: %s", path, err)
587+
}
588+
defer file.Close()
589+
590+
_, err = file.WriteString(content)
591+
if err != nil {
592+
return fmt.Errorf("[ERROR] failed to write data to %s, error: %s", path, err)
593+
}
594+
return nil
595+
}
596+
if err != nil {
597+
return fmt.Errorf("[ERROR] failed to stat file: %s, error: %s", path, err)
598+
}
599+
600+
var file *os.File
601+
if append {
602+
file, err = os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0644)
603+
if err != nil {
604+
return fmt.Errorf("[ERROR] failed to open file for appending: %s, error: %s", path, err)
605+
}
606+
} else {
607+
file, err = os.OpenFile(path, os.O_TRUNC|os.O_WRONLY, 0644)
608+
if err != nil {
609+
return fmt.Errorf("[ERROR] failed to open file for overwriting: %s, error: %s", path, err)
610+
}
611+
}
612+
defer file.Close()
613+
614+
// 写入内容
615+
_, err = file.WriteString(content)
616+
if err != nil {
617+
return fmt.Errorf("[ERROR] failed to write data to %s, error: %s", path, err)
618+
}
619+
return nil
620+
}

0 commit comments

Comments
 (0)