Go语言中实现两次HTTP API间参数动态传递的方法求助
Go语言实现两次依赖HTTP API调用完整流程
先修正结构体定义
你原来的结构体存在关键问题:Go的encoding/json包只能解析首字母大写的导出字段,小写字段无法被外部包访问,会导致解析失败。修正后的两个响应结构体如下:
// 第一个API的响应结构体 type FirstResponse struct { Key string `json:"key"` // 首字母大写,tag对应JSON的key字段 Msg string `json:"msg"` } // 第二个API的响应结构体 type SecondResponse struct { Key string `json:"key"` Content string `json:"content"` }
完整调用流程代码
下面是包含两次HTTP调用、参数传递和响应解析的完整示例,包含必要的错误处理:
package main import ( "encoding/json" "fmt" "net/http" "net/url" ) // 定义两个响应结构体 type FirstResponse struct { Key string `json:"key"` Msg string `json:"msg"` } type SecondResponse struct { Key string `json:"key"` Content string `json:"content"` } func main() { // 第一步:调用第一个API,获取key firstResp, err := http.Get("https://your-first-api-url.com") if err != nil { fmt.Printf("调用第一个API失败: %v\n", err) return } defer firstResp.Body.Close() // 必须关闭响应体,避免资源泄漏 var firstResult FirstResponse if err := json.NewDecoder(firstResp.Body).Decode(&firstResult); err != nil { fmt.Printf("解析第一个API响应失败: %v\n", err) return } // 检查第一个API的返回状态(可选,根据实际需求判断) if firstResult.Msg != "OK" { fmt.Printf("第一个API返回异常: %s\n", firstResult.Msg) return } // 第二步:用获取到的key调用第二个API // 假设第二个API是GET请求,key作为URL参数传递 secondURL, err := url.Parse("https://your-second-api-url.com") if err != nil { fmt.Printf("解析第二个API URL失败: %v\n", err) return } // 构造URL参数 q := secondURL.Query() q.Set("key", firstResult.Key) secondURL.RawQuery = q.Encode() secondResp, err := http.Get(secondURL.String()) if err != nil { fmt.Printf("调用第二个API失败: %v\n", err) return } defer secondResp.Body.Close() var secondResult SecondResponse if err := json.NewDecoder(secondResp.Body).Decode(&secondResult); err != nil { fmt.Printf("解析第二个API响应失败: %v\n", err) return } // 打印最终结果 fmt.Printf("第二个API返回结果: key=%s, content=%s\n", secondResult.Key, secondResult.Content) }
关键补充说明
- 字段导出规则:结构体字段首字母必须大写,否则
encoding/json无法读取和写入该字段,这是Go语言包可见性的硬性规则。 - 响应体关闭:每次HTTP请求后必须用
defer resp.Body.Close()关闭响应体,防止资源泄漏。 - POST请求适配:如果第二个API是POST请求,需要把key放到请求体中,示例代码如下:
// 新增POST请求的参数结构体 type SecondRequest struct { Key string `json:"key"` } // 构造请求体 reqBody, err := json.Marshal(SecondRequest{Key: firstResult.Key}) if err != nil { fmt.Printf("构造请求体失败: %v\n", err) return } // 发起POST请求 secondResp, err := http.Post("https://your-second-api-url.com", "application/json", bytes.NewBuffer(reqBody))
内容的提问来源于stack exchange,提问作者Sri
相关产品推荐
相关产品推荐

