解析JSON时避免在发生任何错误时停止Go程序

时间:2017-07-12 14:49:05

标签: go

如何在解析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的服务器可能会关闭,那么在这种情况下会出现错误“没有这样的主机”并且程序退出,我们如何忽略错误并保持程序运行

  2. 有些情况下,https://siteurl.com/api?lists=1的服务器会发出HTML 404 NOT found错误而不是JSON响应,在这种情况下,它会出现错误“invalid character”<'寻找价值的开端“并且程序退出,我们如何忽略错误并保持程序运行?

1 个答案:

答案 0 :(得分:3)

不要使用log.Fatal - 通过使用该功能,您在遇到错误时明确告诉它崩溃:

  

致命等同于Print(),然后调用os.Exit(1)。

"致命"意味着它所说的,它会杀死这个过程。