英文:
How to handle index out of range in JSON ( Go)
问题
我正在开发一个网络服务,其中一部分是读取请求的主体并尝试解析它。
如果出现错误,例如:if err := json.NewDecoder(body).Decode(r); err !=nil{
,我会记录错误并返回错误信息。
问题在于有时客户端发送一个空的主体,导致出现运行时错误:runtime error: index out of range goroutine 7 [running]:
。我应该如何解决这个问题?
英文:
I'm developing a web service and part of that I read the Request.Body and try to unmarshal it.
if err := json.NewDecoder(body).Decode(r); err !=nil{
log.Error(err)
return err
}
The issue is that sometimes the client is sending an empty body and I get a panic runtime error: index out of range
goroutine 7 [running]:
How am I supposed to mitigate this?
答案1
得分: 0
我正在解析你的代码:
NewDecoder: -
func NewDecoder(r io.Reader) *Decoder
NewDecoder返回一个从r读取数据的新解码器。解码器引入了自己的缓冲区,并且可能从r中读取超出所请求的JSON值的数据。
所以NewDecoder只从r
读取数据。它不关心r
是否为空...
Decode:-
func (dec *Decoder) Decode(v interface{}) error
Decode从输入中读取下一个JSON编码的值,并将其存储在指向v的值中。
有关将JSON转换为Go值的详细信息,请参阅Unmarshal的文档。
要将JSON解组为接口值,Unmarshal将以下之一存储在接口值中:
bool,用于JSON布尔值
float64,用于JSON数字
string,用于JSON字符串
[]interface{},用于JSON数组
map[string]interface{},用于JSON对象
nil,用于JSON null
如果JSON值不适合给定的目标类型,或者JSON数字溢出目标类型,Unmarshal将跳过该字段,并尽力完成解组。如果没有遇到更严重的错误,Unmarshal将返回一个描述最早出现的此类错误的UnmarshalTypeError。
JSON null值通过将Go值设置为nil来解组为接口、映射、指针或切片。因为null在JSON中通常表示“不存在”,所以将JSON null解组为其他任何Go类型都不会对值产生影响,也不会产生错误。
从上面的说明中可以看出,我们不太可能遇到运行时恐慌错误。我正在尝试使用一个示例代码来重现此错误。可能错误来自JSON包内部或者你自己的代码。
英文:
I am decomposing your code:
NewDecoder: -
func NewDecoder(r io.Reader) *Decoder
> NewDecoder returns a new decoder that reads from r. The decoder
> introduces its own buffering and may read data from r beyond the JSON
> values requested.
So NewDecoder only reads data from r
. it's not care, is r
empty...
Decode:-
func (dec *Decoder) Decode(v interface{}) error
> Decode reads the next JSON-encoded value from its input and stores it
> in the value pointed to by v.
>
> See the documentation for Unmarshal for details about the conversion of JSON into a Go value.
To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:
bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null
> If a JSON value is not appropriate for a given target type, or if a
> JSON number overflows the target type, Unmarshal skips that field and
> completes the unmarshalling as best it can. If no more serious errors
> are encountered, Unmarshal returns an UnmarshalTypeError describing
> the earliest such error.
>
> The JSON null value unmarshals into an interface, map, pointer, or
> slice by setting that Go value to nil. Because null is often used in
> JSON to mean “not present,” unmarshaling a JSON null into any other Go
> type has no effect on the value and produces no error.
Reading above statement, it's clear that there is not chances, we get run time panic error. I was experimenting with a sample code to reproduce this ERROR. May error coming from inside the JSON package or your own code.
答案2
得分: -1
var dummy []byte
dummy = make([]byte, 10)
size, _ := body.Read(dummy)
if size > 0 {
if err := json.NewDecoder(body).Decode(r); err != nil {
log.Error(err)
return err
}
}
fmt.Fprintf(w, "%s", "Json 不能为空")// 这里的 w 是 http.ResponseWriter
英文:
var dummy []byte
dummy = make([]byte, 10)
size, _ := body.Read(dummy)
if size > 0 {
if err := json.NewDecoder(body).Decode(r); err != nil {
log.Error(err)
return err
}
fmt.Fprintf(w, "%s", "Json cannot be empty")// where w is http.ResponseWriter
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论