英文:
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。
问题是如何忽略任何错误并避免程序自动停止,例如:
-
当
https://siteurl.com/api?lists=1
上的服务器关闭时,它会给出错误"No such host",并且程序退出,如何忽略该错误并保持程序运行? -
当
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
{"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}]}
My Code is :
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))
}
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 :
-
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? -
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论