在解析 JSON 时,避免 Go 程序在出现任何错误时停止。

huangapple go评论98阅读模式
英文:

While parsing JSON avoid Go program from being stopped in case of any errors

问题

如何在解析以下JSON时忽略错误?

这是示例JSON响应:

{"success":true,"endpoint":"https://api.abcxyz.com","info":
{"Guestconnected":134,"Guestratio":100000.06963,"symbol1":
{"code":"NY","symbol":"*","name":"newyear","codev":391.78161,"symbolAppearsAfter
":false,"local":true},"symbol2":
{"code":"HNY","symbol":"@","name":"HappyNewYear","codev":1000000.0960,"symbolApp
earsAfter":true,"local":false},"latest":
{"value":1597509,"autovalue":"00099cf8da58a36c08f2ef98650ff6043ddfb","height":47
4696,"time":1499527696}},"Allguest":
{"all":4,"filtered":4,"total_invitations":15430,"sent_invitations":15430,"final_
invitations":0},"Guestlist":
[{"GuestCode":"369AR","all":2,"total_invitations":5430,"sent_invitations":5430,"
final_invitations":0,"change":0,"accounts":0},
{"GuestCode":"6POIA96TY","all":2,"total_invitations":10000,"sent_invitations":10
000,"final_invitations":0,"change":0,"accounts":0}]}

我的代码是:

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)


type object struct {
    Success bool `json:"success"`
    Endpoint string `json:"endpoint"`
    Allguest struct {
        All int `json:"all"`
        Filtered int `json:"filtered"`
        TotalInvitations int `json:"total_invitations"`
        SentInvitations int `json:"sent_invitations"`
        FinalInvitations int `json:"final_invitations"`
    } `json:"Allguest"`
    Guestlist []struct {
        GuestCode string `json:"GuestCode"`
        All int `json:"all"`
        TotalInvitations int `json:"total_invitations"`
        SentInvitations int `json:"sent_invitations"`
        FinalInvitations int `json:"final_invitations"`
        Change int `json:"change"`
        Accounts int `json:"accounts"`
    } `json:"Guestlist"`
}

func Newreq(w http.ResponseWriter, r *http.Request) {

uri := "https://siteurl.com/api?lists=1"
res, err := http.Get(uri)
fmt.Println(uri)
if err != nil {
fmt.Println("Error:", err)
    log.Fatal(err)
}
defer res.Body.Close()

var s object
// Using err := gives error no new variables on left side of := during compilation ?
err = json.NewDecoder(res.Body).Decode(&s) 
if err != nil {
    log.Fatal(err)
    fmt.Println("Error:", err)
}
fmt.Println(s.Success)
fmt.Println(s.Allguest.TotalInvitations)
for i := range s.Guestlist {
fmt.Println(s.Guestlist[i].TotalInvitations)
}
}

func main() {

http.HandleFunc("/", Newreq)
    
log.Println("Listening")
log.Fatal(http.ListenAndServe(":8080", nil))
    
}

该程序已经编译并成功运行,如果服务器提供的JSON响应中没有错误。

我正在本地测试,地址为localhost:8080。

问题是如何忽略任何错误并避免程序自动停止,例如:

  1. https://siteurl.com/api?lists=1上的服务器关闭时,它会给出错误"No such host",并且程序退出,如何忽略该错误并保持程序运行?

  2. https://siteurl.com/api?lists=1上的服务器返回HTML 404 NOT found错误而不是JSON响应时,它会给出错误"invalid character '<' looking for beginning of value",并且程序退出,如何忽略该错误并保持程序运行?

英文:

How could I Ignore errors while parsing below JSON

Here is the sample JSON response

{&quot;success&quot;:true,&quot;endpoint&quot;:&quot;https://api.abcxyz.com&quot;,&quot;info&quot;:
{&quot;Guestconnected&quot;:134,&quot;Guestratio&quot;:100000.06963,&quot;symbol1&quot;:
{&quot;code&quot;:&quot;NY&quot;,&quot;symbol&quot;:&quot;*&quot;,&quot;name&quot;:&quot;newyear&quot;,&quot;codev&quot;:391.78161,&quot;symbolAppearsAfter
&quot;:false,&quot;local&quot;:true},&quot;symbol2&quot;:
{&quot;code&quot;:&quot;HNY&quot;,&quot;symbol&quot;:&quot;@&quot;,&quot;name&quot;:&quot;HappyNewYear&quot;,&quot;codev&quot;:1000000.0960,&quot;symbolApp
earsAfter&quot;:true,&quot;local&quot;:false},&quot;latest&quot;:
{&quot;value&quot;:1597509,&quot;autovalue&quot;:&quot;00099cf8da58a36c08f2ef98650ff6043ddfb&quot;,&quot;height&quot;:47
4696,&quot;time&quot;:1499527696}},&quot;Allguest&quot;:
{&quot;all&quot;:4,&quot;filtered&quot;:4,&quot;total_invitations&quot;:15430,&quot;sent_invitations&quot;:15430,&quot;final_
invitations&quot;:0},&quot;Guestlist&quot;:
[{&quot;GuestCode&quot;:&quot;369AR&quot;,&quot;all&quot;:2,&quot;total_invitations&quot;:5430,&quot;sent_invitations&quot;:5430,&quot;
final_invitations&quot;:0,&quot;change&quot;:0,&quot;accounts&quot;:0},
{&quot;GuestCode&quot;:&quot;6POIA96TY&quot;,&quot;all&quot;:2,&quot;total_invitations&quot;:10000,&quot;sent_invitations&quot;:10
000,&quot;final_invitations&quot;:0,&quot;change&quot;:0,&quot;accounts&quot;:0}]}

My Code is :

package main
import (
&quot;encoding/json&quot;
&quot;fmt&quot;
&quot;log&quot;
&quot;net/http&quot;
)
type object struct {
Success bool `json:&quot;success&quot;`
Endpoint string `json:&quot;endpoint&quot;`
Allguest struct {
All int `json:&quot;all&quot;`
Filtered int `json:&quot;filtered&quot;`
TotalInvitations int `json:&quot;total_invitations&quot;`
SentInvitations int `json:&quot;sent_invitations&quot;`
FinalInvitations int `json:&quot;final_invitations&quot;`
} `json:&quot;Allguest&quot;`
Guestlist []struct {
GuestCode string `json:&quot;GuestCode&quot;`
All int `json:&quot;all&quot;`
TotalInvitations int `json:&quot;total_invitations&quot;`
SentInvitations int `json:&quot;sent_invitations&quot;`
FinalInvitations int `json:&quot;final_invitations&quot;`
Change int `json:&quot;change&quot;`
Accounts int `json:&quot;accounts&quot;`
} `json:&quot;Guestlist&quot;`
}
func Newreq(w http.ResponseWriter, r *http.Request) {
uri := &quot;https://siteurl.com/api?lists=1&quot;
res, err := http.Get(uri)
fmt.Println(uri)
if err != nil {
fmt.Println(&quot;Error:&quot;, err)
log.Fatal(err)
}
defer res.Body.Close()
var s object
// Using err := gives error no new variables on left side of := during compilation ?
err = json.NewDecoder(res.Body).Decode(&amp;s) 
if err != nil {
log.Fatal(err)
fmt.Println(&quot;Error:&quot;, err)
}
fmt.Println(s.Success)
fmt.Println(s.Allguest.TotalInvitations)
for i := range s.Guestlist {
fmt.Println(s.Guestlist[i].TotalInvitations)
}
}
func main() {
http.HandleFunc(&quot;/&quot;, Newreq)
log.Println(&quot;Listening&quot;)
log.Fatal(http.ListenAndServe(&quot;:8080&quot;, nil))
}

The Program has been compiled and is running successfully if there is no errors in the JSON response supplied by the server .

I am testing this locally at localhost:8080

The problem is how can we ignore any error and avoid the program from stopping automatically, for example :

  1. There are instances when the server at https://siteurl.com/api?lists=1 can be down then in that case it will give error "No such host" and the program exits, how can we ignore the error and keep the program running?

  2. There are instances when the server at https://siteurl.com/api?lists=1 gives a HTML 404 NOT found error instead of a JSON response, in that case it gives error "invalid character '<' looking for beginning of value" and the program exits, how can we ignore the error and keep the program running?

答案1

得分: 3

不要使用log.Fatal - 使用该函数时,你明确告诉它在遇到错误时崩溃:

Fatal相当于调用Print(),然后调用os.Exit(1)

“Fatal”就是字面意思,它会终止进程。

英文:

Don't use log.Fatal - by using that function you're explicitly telling it to crash when it encounters an error:

> Fatal is equivalent to Print() followed by a call to os.Exit(1).

"Fatal" means what it says, it kills the process.

huangapple
  • 本文由 发表于 2017年7月12日 22:49:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/45061019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定