我在go语言中关于错误处理的方法有些困惑。我已经阅读了很多文章,但仍然无法将它们应用于我的代码结构中。由于我是go的新手,请帮忙解决。
主函数处理两个api:api1和api2。
func main() {
http.HandleFunc("/offers", api1)
http.HandleFunc("/getOffersList", api2)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func api1(w http.ResponseWriter, req *http.Request) {
validateRequestHeader(w, req, "GET")
// code here....
}
func api2(w http.ResponseWriter, req *http.Request) {
validateRequestHeader(w, req, "POST")
//code here....
}
func validateRequestHeader(w http.ResponseWriter, req *http.Request, allowedMethod string) {
// allow cross domain AJAX requests
w.Header().Set("Content-Type", "application/json")
if origin := req.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
// Stop here if its Preflighted OPTIONS request
if req.Method == "OPTIONS" {
return
}
if req.Method != allowedMethod {
response := "Only " + allowedMethod + " requests are allowed"
http.Error(w, response, http.StatusMethodNotAllowed)
return
}
}
在 api1
和 api2
中,都会调用函数 validateRequestHeader
。如果这个函数返回 true,那么在 api1/api2 中将继续执行进一步的代码,而我不希望它这样执行。应该如何处理?
if req.Method != allowedMethod {
response := "Only " + allowedMethod + " requests are allowed"
http.Error(w, response, http.StatusMethodNotAllowed)
return
}
http.Error(w, response, http.StatusMethodNotAllowed) return
- JagrativalidateRequestHeader
方法返回一个错误类型,并在方法调用时检查err != nil
。只有在这种情况下才能继续执行。 - Endre Simo