@@ -2,7 +2,6 @@ package main
2
2
3
3
import (
4
4
"context"
5
- "encoding/json"
6
5
"fmt"
7
6
"io"
8
7
"log"
@@ -89,16 +88,17 @@ func readAndAppendToFile(inputFile, outputFile, appendText string) error {
89
88
return os .WriteFile (outputFile , []byte (modifiedContent ), 0644 )
90
89
}
91
90
92
- func callAPIAndExtractField (ctx context.Context , apiURL string ) (string , error ) {
91
+ func checkAPIReachability (ctx context.Context , apiURL string ) error {
92
+ // 创建带有上下文的 HTTP GET 请求
93
93
req , err := http .NewRequestWithContext (ctx , http .MethodGet , apiURL , nil )
94
94
if err != nil {
95
- return "" , fmt .Errorf ("failed to create request: %w" , err )
95
+ return fmt .Errorf ("failed to create request: %w" , err )
96
96
}
97
97
98
98
client := & http.Client {Timeout : httpTimeout }
99
99
resp , err := client .Do (req )
100
100
if err != nil {
101
- return "" , fmt .Errorf ("failed to make API request: %w" , err )
101
+ return fmt .Errorf ("failed to make API request: %w" , err )
102
102
}
103
103
defer func (Body io.ReadCloser ) {
104
104
err := Body .Close ()
@@ -107,22 +107,12 @@ func callAPIAndExtractField(ctx context.Context, apiURL string) (string, error)
107
107
}
108
108
}(resp .Body )
109
109
110
- body , err := io .ReadAll (resp .Body )
111
- if err != nil {
112
- return "" , fmt .Errorf ("failed to read API response: %w" , err )
113
- }
114
-
115
- var result map [string ]interface {}
116
- if err := json .Unmarshal (body , & result ); err != nil {
117
- return "" , fmt .Errorf ("failed to parse JSON response: %w" , err )
110
+ // 检查响应状态码是否在 200-299 范围内
111
+ if resp .StatusCode < http .StatusOK || resp .StatusCode >= http .StatusMultipleChoices {
112
+ return fmt .Errorf ("API is not reachable, status code: %d" , resp .StatusCode )
118
113
}
119
114
120
- dataField , ok := result ["data" ].(string )
121
- if ! ok {
122
- return "" , fmt .Errorf ("field 'data' not found in API response or is not a string" )
123
- }
124
-
125
- return dataField , nil
115
+ return nil
126
116
}
127
117
128
118
func setOutput (name , value string ) error {
@@ -179,11 +169,11 @@ func main() {
179
169
ctx , cancel := context .WithTimeout (context .Background (), contextTimeout )
180
170
defer cancel ()
181
171
182
- responseField , err := callAPIAndExtractField (ctx , config .ApiURL )
172
+ err = checkAPIReachability (ctx , config .ApiURL )
183
173
if err != nil {
184
174
log .Fatalf ("API request error: %v" , err )
185
175
}
186
- if err := setOutput ("response_field" , responseField ); err != nil {
176
+ if err := setOutput ("response_field" , "API Reachable" ); err != nil {
187
177
log .Fatalf ("Failed to set output: %v" , err )
188
178
}
189
179
}
0 commit comments