Golang中解码响应体到结构体时出现EOF错误的原因
Golang中解码响应体到结构体时出现EOF错误的原因 以下代码用于从服务器获取数据,并将数据存入结构体。
数据可以正确获取,但在将返回的数据解码到结构体时,我遇到了 err: EOF 错误:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
type SKUcard struct {
BarCode, SKUCode, VendorCode, RegistrationDate, VendorName, BrandName, ContactPerson,
ContactNumber, ItemName, ItemImage, NetWeight, CartoonPack, StorageTemperature, ShelfLife,
ShelfPrice, KottofCost, SupplyType, CoveredAreas, MinimumOrderQty, ContractDate, ReturnPolicy, Notes, InActive string
}
func main() {
req, _ := http.NewRequest("GET", "https://script.google.com/macros/s/AKfycbzw0TKWycxeB5sx1wIefAiEHeYQt2mVuM-NAZTccxedhyntdv8FvcUteOZ2k03wRHGE/exec?", nil)
q := req.URL.Query()
q.Add("barcode", "6287029390129")
//q.Add("another_thing", "foo & bar")
req.URL.RawQuery = q.Encode()
fmt.Println(req.URL.String())
// resp, err := http.Get(req.URL.String())
resp, err := http.DefaultClient.Do(req)
_ = req.URL.RawQuery
if err != nil {
log.Fatalln(err)
}
//We Read the response body on the line below.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
//Convert the body to type string
sb := string(body)
log.Printf(sb)
var target = new(SKUcard)
err = json.NewDecoder(resp.Body).Decode(target)
if err != nil {
fmt.Println("err:", err)
}
log.Printf(target.BarCode)
}
更多关于Golang中解码响应体到结构体时出现EOF错误的原因的实战教程也可以访问 https://www.itying.com/category-94-b0.html
2 回复
根据我所见,您从Body中读取了两次
ioutil.ReadAll(resp.Body)json.NewDecoder(resp.Body)
由于Body是一个ReadCloser,我认为第二次读取时您会发现它已经被读取过了。
所以,要么:
- 移除第一次读取
ioutil.ReadAll - 在一个初始化为
body的读取缓冲区上使用json解码器
buf := bytes.NewBuffer(body)
err = json.NewDecode(buf).Decode(target)
另外,我建议在处理响应体之前,始终检查响应的StatusCode。

