gpt4 book ai didi

http - 将 interface{} 参数转换为 Go 中的 *http.Request 或 *http.Response

转载 作者:IT王子 更新时间:2023-10-29 01:51:18 33 4
gpt4 key购买 nike

我打算创建一个 util 函数,它将读取请求/响应的主体并将其返回。
这是我目前所做的:

func GetBody(in interface{}) []byte {
var body io.Reader
var statusCode int

switch v := in.(type) {
case *http.Request, *http.Response:
body = v.Body
statusCode = v.StatusCode
default:
log.Fatal("Only http.Request and http.Response parameters can be accepted to parse body")
}

if statusCode != 200 {
log.Fatalf("Received status code [%d] instead of [200]", statusCode)
}

body, err := ioutil.ReadAll(body)
if err != nil {
log.Fatal(err)
}
return body
}

但我收到编译器错误:v.Body undefined (type interface {} is interface with no methods)
我是不是遗漏了什么,或者不可能制作一个通用函数来同时为 *http.Request*http.Response

服务

最佳答案

这是因为双重case

v 仍然是一个接口(interface){},因为它可以是一个*http.Request 或一个*http.Response

switch v := in.(type) {
case *http.Request
body = v.Body
statusCode = v.StatusCode
case *http.Response:
body = v.Body
statusCode = v.StatusCode
default:
log.Fatal("Only http.Request and http.Response parameters can be accepted to parse body")
}

这应该可行

关于http - 将 interface{} 参数转换为 Go 中的 *http.Request 或 *http.Response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32454490/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com