-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcoverage.html
More file actions
3944 lines (3342 loc) · 159 KB
/
coverage.html
File metadata and controls
3944 lines (3342 loc) · 159 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>httpclient: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">github.com/birdmichael/RenderAPI/cmd/httpclient/main.go (0.0%)</option>
<option value="file1">github.com/birdmichael/RenderAPI/examples/advanced/main.go (0.0%)</option>
<option value="file2">github.com/birdmichael/RenderAPI/examples/basic/main.go (0.0%)</option>
<option value="file3">github.com/birdmichael/RenderAPI/examples/template_file/main.go (0.0%)</option>
<option value="file4">github.com/birdmichael/RenderAPI/examples/template_functions/main.go (0.0%)</option>
<option value="file5">github.com/birdmichael/RenderAPI/internal/utils/utils.go (14.6%)</option>
<option value="file6">github.com/birdmichael/RenderAPI/main.go (0.0%)</option>
<option value="file7">github.com/birdmichael/RenderAPI/pkg/client/client.go (26.8%)</option>
<option value="file8">github.com/birdmichael/RenderAPI/pkg/config/config.go (88.2%)</option>
<option value="file9">github.com/birdmichael/RenderAPI/pkg/hooks/cmd_hook.go (73.0%)</option>
<option value="file10">github.com/birdmichael/RenderAPI/pkg/hooks/custom_hook.go (77.8%)</option>
<option value="file11">github.com/birdmichael/RenderAPI/pkg/hooks/hooks.go (32.1%)</option>
<option value="file12">github.com/birdmichael/RenderAPI/pkg/hooks/js_hook.go (60.7%)</option>
<option value="file13">github.com/birdmichael/RenderAPI/pkg/template/builtin_functions.go (70.5%)</option>
<option value="file14">github.com/birdmichael/RenderAPI/pkg/template/template.go (90.7%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">no coverage</span>
<span class="cov1">low coverage</span>
<span class="cov2">*</span>
<span class="cov3">*</span>
<span class="cov4">*</span>
<span class="cov5">*</span>
<span class="cov6">*</span>
<span class="cov7">*</span>
<span class="cov8">*</span>
<span class="cov9">*</span>
<span class="cov10">high coverage</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">// httpclient命令行工具 - 一个灵活的HTTP请求工具,支持模板文件
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"strings"
"github.com/birdmichael/RenderAPI/internal/utils"
"github.com/birdmichael/RenderAPI/pkg/client"
"github.com/birdmichael/RenderAPI/pkg/config"
"github.com/birdmichael/RenderAPI/pkg/hooks"
)
func main() <span class="cov0" title="0">{
// 命令行参数
configPath := flag.String("config", "config.json", "配置文件路径")
method := flag.String("method", "GET", "HTTP方法 (GET, POST, PUT, DELETE)")
url := flag.String("url", "", "请求URL")
path := flag.String("path", "", "请求路径")
templateFile := flag.String("template", "", "模板文件路径")
dataFile := flag.String("data", "", "数据文件路径")
outputFile := flag.String("output", "", "输出文件路径")
rawData := flag.String("raw", "", "原始请求数据")
scriptFile := flag.String("script", "", "前置处理脚本路径")
flag.Parse()
// 加载配置
cfg, err := config.LoadConfig(*configPath)
if err != nil </span><span class="cov0" title="0">{
// 如果配置文件不存在,使用默认配置
fmt.Printf("警告: 无法加载配置,使用默认值: %v\n", err)
cfg = config.DefaultConfig()
}</span>
// 创建HTTP客户端
<span class="cov0" title="0">baseURL := cfg.BaseURL
if *url != "" </span><span class="cov0" title="0">{
baseURL = *url
}</span>
<span class="cov0" title="0">httpClient := client.NewClient(baseURL, cfg.GetTimeout())
// 设置默认请求头
for key, value := range cfg.DefaultHeaders </span><span class="cov0" title="0">{
httpClient.SetHeader(key, value)
}</span>
// 添加钩子
<span class="cov0" title="0">if cfg.EnableLogging </span><span class="cov0" title="0">{
httpClient.AddBeforeHook(&hooks.LoggingHook{})
httpClient.AddAfterHook(&hooks.ResponseLogHook{})
}</span>
<span class="cov0" title="0">if cfg.AuthToken != "" </span><span class="cov0" title="0">{
httpClient.AddBeforeHook(&hooks.AuthHook{Token: cfg.AuthToken})
}</span>
// 添加脚本钩子(如果指定)
<span class="cov0" title="0">if *scriptFile != "" </span><span class="cov0" title="0">{
if err := httpClient.AddJSHookFromFile(*scriptFile, false, 30); err != nil </span><span class="cov0" title="0">{
fmt.Printf("添加脚本钩子失败: %v\n", err)
os.Exit(1)
}</span>
}
<span class="cov0" title="0">var resp *http.Response
ctx := context.Background()
// 使用模板文件和数据文件
if *templateFile != "" && *dataFile != "" </span><span class="cov0" title="0">{
resp, err = httpClient.ExecuteTemplateWithDataFile(ctx, *templateFile, *dataFile)
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("执行模板失败: %v\n", err)
os.Exit(1)
}</span>
} else<span class="cov0" title="0"> {
// 准备请求体
var requestBody []byte
if *templateFile != "" </span><span class="cov0" title="0">{
// 加载模板
data, err := os.ReadFile(*templateFile)
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("读取模板文件失败: %v\n", err)
os.Exit(1)
}</span>
// 检查是否为完整模板格式(包含request和body)
<span class="cov0" title="0">var tmplStruct struct {
Request interface{} `json:"request"`
Body interface{} `json:"body"`
}
if err := json.Unmarshal(data, &tmplStruct); err == nil && tmplStruct.Request != nil </span><span class="cov0" title="0">{
// 如果是完整模板,使用上下文执行
var templateData map[string]interface{}
if *dataFile != "" </span><span class="cov0" title="0">{
templateData, err = utils.LoadDataFromFile(*dataFile)
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("加载数据文件失败: %v\n", err)
os.Exit(1)
}</span>
}
<span class="cov0" title="0">resp, err = httpClient.ExecuteTemplateJSON(ctx, string(data), templateData)
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("执行模板失败: %v\n", err)
os.Exit(1)
}</span>
} else<span class="cov0" title="0"> {
// 使用模板引擎处理非完整模板
templateEngine := httpClient.GetTemplateEngine()
// 添加模板
err = templateEngine.AddTemplate(*templateFile, string(data))
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("添加模板失败: %v\n", err)
os.Exit(1)
}</span>
// 加载数据
<span class="cov0" title="0">var templateData interface{}
if *dataFile != "" </span><span class="cov0" title="0">{
dataContent, err := os.ReadFile(*dataFile)
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("读取数据文件失败: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">err = json.Unmarshal(dataContent, &templateData)
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("解析数据文件失败: %v\n", err)
os.Exit(1)
}</span>
}
// 渲染模板
<span class="cov0" title="0">requestBody, err = templateEngine.RenderJSONTemplate(*templateFile, templateData)
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("渲染模板失败: %v\n", err)
os.Exit(1)
}</span>
}
} else<span class="cov0" title="0"> if *rawData != "" </span><span class="cov0" title="0">{
// 使用原始数据
requestBody = []byte(*rawData)
}</span>
// 如果尚未发送请求,使用传统方式发送
<span class="cov0" title="0">if resp == nil && (len(requestBody) > 0 || *method == "GET" || *method == "DELETE") </span><span class="cov0" title="0">{
// 发送请求
httpMethod := strings.ToUpper(*method)
switch httpMethod </span>{
case "GET":<span class="cov0" title="0">
resp, err = httpClient.Get(*path)</span>
case "POST":<span class="cov0" title="0">
resp, err = httpClient.Post(*path, requestBody)</span>
case "PUT":<span class="cov0" title="0">
resp, err = httpClient.Put(*path, requestBody)</span>
case "DELETE":<span class="cov0" title="0">
resp, err = httpClient.Delete(*path)</span>
default:<span class="cov0" title="0">
fmt.Printf("不支持的HTTP方法: %s\n", httpMethod)
os.Exit(1)</span>
}
<span class="cov0" title="0">if err != nil </span><span class="cov0" title="0">{
fmt.Printf("请求失败: %v\n", err)
os.Exit(1)
}</span>
}
}
<span class="cov0" title="0">if resp == nil </span><span class="cov0" title="0">{
fmt.Println("错误: 未发送任何请求")
os.Exit(1)
}</span>
// 读取响应
<span class="cov0" title="0">responseBody, err := utils.ReadResponseBody(resp)
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("读取响应失败: %v\n", err)
os.Exit(1)
}</span>
// 输出结果
<span class="cov0" title="0">if *outputFile != "" </span><span class="cov0" title="0">{
err = os.WriteFile(*outputFile, responseBody, 0644)
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("写入输出文件失败: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">fmt.Printf("响应已保存到: %s\n", *outputFile)</span>
} else<span class="cov0" title="0"> {
fmt.Printf("状态码: %d\n", resp.StatusCode)
fmt.Printf("响应头:\n")
for key, values := range resp.Header </span><span class="cov0" title="0">{
fmt.Printf(" %s: %s\n", key, strings.Join(values, ", "))
}</span>
<span class="cov0" title="0">fmt.Printf("响应体:\n%s\n", string(responseBody))</span>
}
}
</pre>
<pre class="file" id="file1" style="display: none">// Advanced example - 展示RenderAPI的高级功能
package main
import (
"context"
"fmt"
"net/http"
"os"
"path/filepath"
"time"
"github.com/birdmichael/RenderAPI/internal/utils"
"github.com/birdmichael/RenderAPI/pkg/client"
"github.com/birdmichael/RenderAPI/pkg/hooks"
)
// 自定义钩子
type CustomHook struct{}
func (h *CustomHook) Before(req *http.Request) (*http.Request, error) <span class="cov0" title="0">{
fmt.Println("[自定义钩子] 请求前处理")
// 添加自定义请求头
req.Header.Set("X-Custom-Header", "custom-value")
return req, nil
}</span>
// BeforeAsync 异步执行请求前处理
func (h *CustomHook) BeforeAsync(req *http.Request) (chan *http.Request, chan error) <span class="cov0" title="0">{
reqChan := make(chan *http.Request, 1)
errChan := make(chan error, 1)
go func() </span><span class="cov0" title="0">{
modifiedReq, err := h.Before(req)
if err != nil </span><span class="cov0" title="0">{
errChan <- err
return
}</span>
<span class="cov0" title="0">reqChan <- modifiedReq</span>
}()
<span class="cov0" title="0">return reqChan, errChan</span>
}
// 添加钩子
func setupHooks(c *client.Client) <span class="cov0" title="0">{
// 添加日志钩子
c.AddBeforeHook(&hooks.LoggingHook{})
c.AddAfterHook(&hooks.ResponseLogHook{})
// 添加自定义钩子
c.AddBeforeHook(&CustomHook{})
// 添加字段转换钩子(将"user"字段转换为"phone")
c.AddBeforeHook(&hooks.FieldTransformHook{})
}</span>
func main() <span class="cov0" title="0">{
// 创建配置
baseURL := "https://httpbin.org"
timeout := 30 * time.Second
// 创建客户端
apiClient := client.NewClient(baseURL, timeout)
// 设置默认头
apiClient.SetHeader("User-Agent", "RenderAPI-Advanced-Example")
apiClient.SetHeader("Content-Type", "application/json")
// 设置钩子
setupHooks(apiClient)
// 创建和使用上下文
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
fmt.Println("\n=== 1. 从文件加载模板和数据 ===")
// 准备示例文件路径
exPath, err := os.Executable()
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("获取可执行文件路径失败: %v\n", err)
exPath = "."
}</span>
<span class="cov0" title="0">exDir := filepath.Dir(exPath)
templateFile := filepath.Join(exDir, "template.json")
dataFile := filepath.Join(exDir, "data.json")
// 创建示例文件
createExampleFiles(templateFile, dataFile)
// 执行模板
resp, err := apiClient.ExecuteTemplateWithDataFile(ctx, templateFile, dataFile)
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("执行模板失败: %v\n", err)
}</span> else<span class="cov0" title="0"> {
body, _ := utils.ReadResponseBody(resp)
fmt.Printf("\n状态码: %d\n", resp.StatusCode)
prettyBody, _ := utils.PrettyJSON(body)
fmt.Printf("响应体:\n%s\n", string(prettyBody))
}</span>
<span class="cov0" title="0">fmt.Println("\n=== 2. 使用字段转换钩子 ===")
// 准备请求体,其中包含"user"字段(会被钩子转换为"phone")
jsonBody := []byte(`{
"user": "13800138000",
"password": "secret123"
}`)
resp, err = apiClient.Post("/post", jsonBody)
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("请求失败: %v\n", err)
}</span> else<span class="cov0" title="0"> {
body, _ := utils.ReadResponseBody(resp)
fmt.Printf("\n状态码: %d\n", resp.StatusCode)
prettyBody, _ := utils.PrettyJSON(body)
fmt.Printf("响应体:\n%s\n", string(prettyBody))
}</span>
// 清理示例文件
<span class="cov0" title="0">os.Remove(templateFile)
os.Remove(dataFile)</span>
}
// 创建示例文件
func createExampleFiles(templateFile, dataFile string) <span class="cov0" title="0">{
// 模板文件
templateContent := `{
"request": {
"method": "POST",
"path": "/post",
"headers": {
"Content-Type": "application/json",
"X-Template-Header": "{{.header_value}}"
}
},
"body": {
"username": "{{.username}}",
"email": "{{.email}}",
"age": {{.age}},
"is_active": {{.is_active}},
"registration_date": "{{.registration_date}}",
"interests": [{{range $index, $item := .interests}}{{if $index}}, {{end}}"{{$item}}"{{end}}]
}
}`
// 数据文件
dataContent := `{
"username": "测试用户",
"email": "test@example.com",
"age": 28,
"is_active": true,
"registration_date": "2023-05-15",
"interests": ["编程", "阅读", "旅行"],
"header_value": "template-header-value"
}`
// 写入文件
os.WriteFile(templateFile, []byte(templateContent), 0644)
os.WriteFile(dataFile, []byte(dataContent), 0644)
}</span>
</pre>
<pre class="file" id="file2" style="display: none">// Basic example - 展示RenderAPI的基本用法
package main
import (
"context"
"fmt"
"os"
"github.com/birdmichael/RenderAPI/pkg/client"
)
func main() <span class="cov0" title="0">{
// 创建新的API客户端
apiClient := client.NewClient("https://httpbin.org", 30)
// 添加默认请求头
apiClient.SetHeader("User-Agent", "RenderAPI-Example")
apiClient.SetHeader("Content-Type", "application/json")
fmt.Println("=== 发送GET请求 ===")
resp, err := apiClient.Get("/get")
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("请求失败: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">body, err := client.ReadResponseBody(resp)
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("读取响应失败: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">fmt.Printf("状态码: %d\n", resp.StatusCode)
fmt.Printf("响应体:\n%s\n\n", string(body))
// 发送POST请求
fmt.Println("=== 发送POST请求 ===")
postData := []byte(`{"name": "test", "value": 123}`)
resp, err = apiClient.Post("/post", postData)
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("请求失败: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">body, err = client.ReadResponseBody(resp)
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("读取响应失败: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">fmt.Printf("状态码: %d\n", resp.StatusCode)
fmt.Printf("响应体:\n%s\n\n", string(body))
// 使用模板渲染
fmt.Println("=== 使用模板渲染 ===")
templateJSON := `{
"request": {
"method": "POST",
"url": "https://httpbin.org",
"path": "/post",
"headers": {
"Content-Type": "application/json"
}
},
"body": {
"name": "{{.name}}",
"value": {{.value}},
"items": [{{range $index, $item := .items}}{{if $index}}, {{end}}"{{$item}}"{{end}}]
}
}`
templateData := map[string]interface{}{
"name": "template-test",
"value": 456,
"items": []string{"item1", "item2", "item3"},
}
ctx := context.Background()
resp, err = apiClient.ExecuteTemplateJSON(ctx, templateJSON, templateData)
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("执行模板失败: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">body, err = client.ReadResponseBody(resp)
if err != nil </span><span class="cov0" title="0">{
fmt.Printf("读取响应失败: %v\n", err)
os.Exit(1)
}</span>
<span class="cov0" title="0">fmt.Printf("状态码: %d\n", resp.StatusCode)
fmt.Printf("响应体:\n%s\n", string(body))</span>
}
</pre>
<pre class="file" id="file3" style="display: none">// 这是导入main包,但实际运行需要链接目标项目的主要实现文件
// 通过build.sh将相关文件链接到一起编译
package main
import (
"context"
"fmt"
"log"
"net/http"
"time"
"github.com/birdmichael/RenderAPI/pkg/client"
"github.com/birdmichael/RenderAPI/pkg/hooks"
)
// 这个示例展示了如何使用新的文件传入设计
// 通过直接读取模板文件和数据文件来执行HTTP请求
func main() <span class="cov0" title="0">{
// 创建HTTP客户端
httpClient := client.NewClient("https://httpbin.org", 30*time.Second)
// 设置默认请求头
httpClient.SetHeader("X-Custom-Header", "CustomValue")
// 添加日志钩子
loggingHook := &hooks.CustomFunctionHook{
BeforeFn: func(req *http.Request) (*http.Request, error) </span><span class="cov0" title="0">{
fmt.Printf("正在发送 %s 请求到 %s\n", req.Method, req.URL.String())
return req, nil
}</span>,
}
<span class="cov0" title="0">responseLogHook := &hooks.CustomFunctionHook{
AfterFn: func(resp *http.Response) (*http.Response, error) </span><span class="cov0" title="0">{
fmt.Printf("收到响应: 状态码 %d\n", resp.StatusCode)
return resp, nil
}</span>,
}
<span class="cov0" title="0">httpClient.AddBeforeHook(loggingHook)
httpClient.AddAfterHook(responseLogHook)
fmt.Println("=== 示例1: 使用模板文件和数据文件 ===")
// 使用模板文件和数据文件
resp, err := httpClient.ExecuteTemplateWithDataFile(
context.Background(),
"post_template.json",
"post_data.json",
)
if err != nil </span><span class="cov0" title="0">{
log.Fatalf("请求失败: %v", err)
}</span>
// 读取响应
<span class="cov0" title="0">body, err := client.ReadResponseBody(resp)
if err != nil </span><span class="cov0" title="0">{
log.Fatalf("读取响应失败: %v", err)
}</span>
<span class="cov0" title="0">fmt.Printf("状态码: %d\n", resp.StatusCode)
fmt.Printf("响应体: %s\n", string(body))
fmt.Println("\n=== 示例2: 使用直接的JSON模板字符串 ===")
// 使用JSON模板字符串
templateJSON := `{
"request": {
"method": "POST",
"baseURL": "https://httpbin.org",
"path": "/post",
"headers": {
"Content-Type": "application/json"
}
},
"body": {
"name": "{{.Name}}",
"email": "{{.Email}}",
"message": "{{.Message}}"
}
}`
// 定义数据
data := map[string]interface{}{
"Name": "李四",
"Email": "lisi@example.com",
"Message": "这是一条测试消息",
}
// 执行模板
resp2, err := httpClient.ExecuteTemplateJSON(
context.Background(),
templateJSON,
data,
)
if err != nil </span><span class="cov0" title="0">{
log.Fatalf("请求失败: %v", err)
}</span>
// 读取响应
<span class="cov0" title="0">body2, err := client.ReadResponseBody(resp2)
if err != nil </span><span class="cov0" title="0">{
log.Fatalf("读取响应失败: %v", err)
}</span>
<span class="cov0" title="0">fmt.Printf("状态码: %d\n", resp2.StatusCode)
fmt.Printf("响应体: %s\n", string(body2))</span>
}
</pre>
<pre class="file" id="file4" style="display: none">// 该示例展示如何使用RenderAPI的内置模板函数
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"os"
"github.com/birdmichael/RenderAPI/pkg/template"
)
func main() <span class="cov0" title="0">{
// 创建新的模板引擎
engine := template.NewEngine()
// 使用字符串操作函数的模板
stringTemplate := `{
"profile": {
"username": "{{ toUpper .username }}",
"display_name": "{{ title .name }}",
"email": "{{ toLower .email }}",
"bio": "{{ trim .bio }}",
"url_safe_username": "{{ urlEncode .username }}",
"html_bio": "{{ htmlEscape .htmlBio }}",
"admin_role": "{{ index .roles 1 }}"
}
}`
// 使用日期和数学函数的模板
mathTemplate := `{
"calculation": {
"num1": {{ .num1 }},
"num2": {{ .num2 }},
"add": {{ add .num1 .num2 }},
"subtract": {{ sub .num1 .num2 }},
"multiply": {{ mul .num1 .num2 }},
"divide": {{ div .num1 .num2 }},
"max": {{ max .num1 .num2 }},
"min": {{ min .num1 .num2 }},
"round": {{ round .float }},
"ceil": {{ ceil .float }},
"floor": {{ floor .float }},
"random": {{ randInt 1 100 }}
}
}`
// 使用条件函数的模板
conditionTemplate := `{
"user": {
"name": "{{ .name }}",
"nickname": "{{ defaultValue .nickname "匿名用户" }}",
"status": "{{ ternary .active "活跃" "不活跃" }}",
"access_level": "{{ coalesce .level .default_level "普通用户" }}",
"premium": {{ and .active .premium }}
}
}`
// 添加模板
err := engine.AddTemplate("string-template", stringTemplate)
if err != nil </span><span class="cov0" title="0">{
log.Fatalf("添加字符串模板失败: %v", err)
}</span>
<span class="cov0" title="0">err = engine.AddTemplate("math-template", mathTemplate)
if err != nil </span><span class="cov0" title="0">{
log.Fatalf("添加数学模板失败: %v", err)
}</span>
<span class="cov0" title="0">err = engine.AddTemplate("condition-template", conditionTemplate)
if err != nil </span><span class="cov0" title="0">{
log.Fatalf("添加条件模板失败: %v", err)
}</span>
// 准备字符串操作示例数据
<span class="cov0" title="0">stringData := map[string]interface{}{
"username": "john_doe",
"name": "john doe",
"email": "JOHN.DOE@EXAMPLE.COM",
"bio": " 这是一个简介,包含了一些信息 ",
"htmlBio": "<div>这是HTML内容</div>",
"roles": []string{"user", "admin", "editor"},
}
// 准备数学示例数据
mathData := map[string]interface{}{
"num1": 10.0,
"num2": 5.0,
"float": 3.75,
}
// 准备条件示例数据
conditionData := map[string]interface{}{
"name": "张三",
"nickname": "",
"active": true,
"premium": true,
"level": nil,
"default_level": "高级用户",
}
// 执行字符串模板
stringResult, err := engine.Execute("string-template", stringData)
if err != nil </span><span class="cov0" title="0">{
log.Fatalf("执行字符串模板失败: %v", err)
}</span>
// 执行数学模板
<span class="cov0" title="0">mathResult, err := engine.Execute("math-template", mathData)
if err != nil </span><span class="cov0" title="0">{
log.Fatalf("执行数学模板失败: %v", err)
}</span>
// 执行条件模板
<span class="cov0" title="0">conditionResult, err := engine.Execute("condition-template", conditionData)
if err != nil </span><span class="cov0" title="0">{
log.Fatalf("执行条件模板失败: %v", err)
}</span>
// 格式化输出结果
<span class="cov0" title="0">stringJson := formatJSON(stringResult)
mathJson := formatJSON(mathResult)
conditionJson := formatJSON(conditionResult)
// 输出结果
fmt.Println("=== 字符串操作示例 ===")
fmt.Println(stringJson)
fmt.Println()
fmt.Println("=== 数学运算示例 ===")
fmt.Println(mathJson)
fmt.Println()
fmt.Println("=== 条件逻辑示例 ===")
fmt.Println(conditionJson)
fmt.Println()
// 保存输出到文件
err = saveToFile("string_output.json", stringJson)
if err != nil </span><span class="cov0" title="0">{
log.Printf("保存字符串输出失败: %v", err)
}</span>
<span class="cov0" title="0">err = saveToFile("math_output.json", mathJson)
if err != nil </span><span class="cov0" title="0">{
log.Printf("保存数学输出失败: %v", err)
}</span>
<span class="cov0" title="0">err = saveToFile("condition_output.json", conditionJson)
if err != nil </span><span class="cov0" title="0">{
log.Printf("保存条件输出失败: %v", err)
}</span>
<span class="cov0" title="0">fmt.Println("所有示例已运行完成,输出已保存到JSON文件")</span>
}
// 格式化JSON
func formatJSON(data string) string <span class="cov0" title="0">{
var out bytes.Buffer
err := json.Indent(&out, []byte(data), "", " ")
if err != nil </span><span class="cov0" title="0">{
return data
}</span>
<span class="cov0" title="0">return out.String()</span>
}
// 保存到文件
func saveToFile(filename, content string) error <span class="cov0" title="0">{
return os.WriteFile(filename, []byte(content), 0644)
}</span>
</pre>
<pre class="file" id="file5" style="display: none">// Package utils 提供内部工具函数
package utils
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
)
// PrettyJSON 格式化JSON字符串
func PrettyJSON(data []byte) ([]byte, error) <span class="cov0" title="0">{
var obj interface{}
err := json.Unmarshal(data, &obj)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov0" title="0">return json.MarshalIndent(obj, "", " ")</span>
}
// ReadResponseBody 读取HTTP响应体
func ReadResponseBody(resp *http.Response) ([]byte, error) <span class="cov0" title="0">{
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}</span>
// LoadDataFromFile 从文件加载JSON数据
func LoadDataFromFile(filePath string) (map[string]interface{}, error) <span class="cov8" title="1">{
data, err := os.ReadFile(filePath)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">var result map[string]interface{}
err = json.Unmarshal(data, &result)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">return result, nil</span>
}
// SaveDataToFile 保存数据到文件
func SaveDataToFile(filePath string, data interface{}) error <span class="cov0" title="0">{
jsonData, err := json.MarshalIndent(data, "", " ")
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">return os.WriteFile(filePath, jsonData, 0644)</span>
}
// LogHTTPRequest 记录HTTP请求信息
func LogHTTPRequest(req *http.Request, body []byte) <span class="cov0" title="0">{
fmt.Printf("[请求] %s %s\n", req.Method, req.URL.String())
if len(req.Header) > 0 </span><span class="cov0" title="0">{
fmt.Println("请求头:")
for k, v := range req.Header </span><span class="cov0" title="0">{
fmt.Printf(" %s: %s\n", k, strings.Join(v, ", "))
}</span>
}
<span class="cov0" title="0">if len(body) > 0 </span><span class="cov0" title="0">{
fmt.Println("请求体:")
prettyBody, err := PrettyJSON(body)
if err == nil </span><span class="cov0" title="0">{
fmt.Println(string(prettyBody))
}</span> else<span class="cov0" title="0"> {
fmt.Println(string(body))
}</span>
}
}
// LogHTTPResponse 记录HTTP响应信息
func LogHTTPResponse(resp *http.Response, body []byte) <span class="cov0" title="0">{
fmt.Printf("[响应] 状态码: %d\n", resp.StatusCode)
if len(resp.Header) > 0 </span><span class="cov0" title="0">{
fmt.Println("响应头:")
for k, v := range resp.Header </span><span class="cov0" title="0">{
fmt.Printf(" %s: %s\n", k, strings.Join(v, ", "))
}</span>
}
<span class="cov0" title="0">if len(body) > 0 </span><span class="cov0" title="0">{
fmt.Println("响应体:")
prettyBody, err := PrettyJSON(body)
if err == nil </span><span class="cov0" title="0">{
fmt.Println(string(prettyBody))
}</span> else<span class="cov0" title="0"> {
fmt.Println(string(body))
}</span>
}
}
</pre>
<pre class="file" id="file6" style="display: none">// RenderAPI 主程序入口
// 提供命令行工具功能,用于发送模板驱动的HTTP请求
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"os"
"github.com/birdmichael/RenderAPI/pkg/client"
"github.com/birdmichael/RenderAPI/pkg/config"
)
func main() <span class="cov0" title="0">{
// 定义命令行参数
baseURL := flag.String("url", "", "API基础URL")
templateFile := flag.String("template", "", "模板文件路径")
dataFile := flag.String("data", "", "数据文件路径")
configFile := flag.String("config", "", "配置文件路径")
token := flag.String("token", "", "认证令牌")
timeout := flag.Int("timeout", 30, "请求超时时间(秒)")
verbose := flag.Bool("verbose", false, "启用详细日志")
scriptFile := flag.String("script", "", "JavaScript脚本文件路径")
method := flag.String("method", "GET", "HTTP方法(不使用模板时)")
path := flag.String("path", "", "API路径(不使用模板时)")
output := flag.String("output", "", "保存响应到文件")
rawData := flag.String("raw", "", "原始请求数据(JSON格式)")
// 解析命令行参数
flag.Parse()
if *baseURL == "" </span><span class="cov0" title="0">{
fmt.Println("错误: 必须指定API基础URL")
flag.Usage()
os.Exit(1)
}</span>