我正在使用 Go 为 Web 应用程序构建 SDK。
我想知道向 SDK 用户返回数据的最佳形式是什么。
例如,下面是一个接受 http.Request 对象的函数。该函数应返回的首选对象/结构是什么?
func runRequest(request *http.Request) map[string]interface{} {
resp, err := http.DefaultClient.Do(request)
//handle error
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
var data map[string]interface{}
err2 := json.Unmarshal([]byte(body), &data)
//handle error
return data
}
最佳答案
对于这个简单的示例,您可以使用 json.Unmarshal
使用的相同方法。也就是说,您的函数采用一个指向您想要将响应正文解码到的值的指针。
func RunRequest(request *http.Request, dst interface{}) error {
resp, err := http.DefaultClient.Do(request)
if err != nil {
return err
}
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(dst)
}
关于oop - 戈兰 : What to return when building an SDK to interact with a Web API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50804385/