@@ -5,18 +5,21 @@ import (
5
5
"encoding/json"
6
6
"fmt"
7
7
"io"
8
+ "log"
8
9
"net/url"
9
10
"reflect"
10
11
"strconv"
11
12
"strings"
12
13
14
+ "github.com/hashicorp/go-multierror"
13
15
"github.com/hashicorp/go-uuid"
14
16
"github.com/tidwall/gjson"
15
17
16
18
"github.com/chnsz/golangsdk"
17
19
"github.com/chnsz/golangsdk/pagination"
18
20
19
21
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/helper/filters"
22
+ "github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils"
20
23
)
21
24
22
25
type HttpHelper struct {
@@ -265,6 +268,55 @@ func (c *HttpHelper) ExtractInto(to any) error {
265
268
return json .Unmarshal (c .responseBody , to )
266
269
}
267
270
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
+
268
320
func (c * HttpHelper ) requestWithPage () {
269
321
body := make (map [string ]any )
270
322
pager := pagination .NewPager (c .client , c .url , c .pager )
0 commit comments