去Http错误处理

Jag*_*ati 4 error-handling 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
    }
}
Run Code Online (Sandbox Code Playgroud)

在这两个api1api2,函数validateRequestHeader获取调用.如果这是真的,那么在api1/api2中,进一步的代码正在执行,我不想要.应如何处理?

if req.Method != allowedMethod {
        response := "Only " + allowedMethod + " requests are allowed"
        http.Error(w, response, http.StatusMethodNotAllowed)
        return
    }
Run Code Online (Sandbox Code Playgroud)

Emi*_*l H 7

这篇博文介绍了如何链接多个处理函数的一些细节,这就是你应该做的事情.这样,您就可以拥有验证处理程序,日志处理程序,授权处理程序等,并将它们链接在一起.

实质上

func validator(next http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, req *http.Request) {
            if isRequestValid(req) {
                // a valid request is passed on to next handler
                next.ServeHTTP(w, req)
            } else {
                // otherwise, respond with an error
                http.Error(w, "Bad request - Go away!", 400)
            }
    }
    return http.HandlerFunc(fn)
}

func api1() http.Handler {
    fn := func(w http.ResponseWriter, req *http.Request) {
            // api 1 code
    }
    return http.HandlerFunc(fn)
}

func api2() http.Handler {
    fn := func(w http.ResponseWriter, req *http.Request) {
            // api 2 code
    }
    return http.HandlerFunc(fn)
}
Run Code Online (Sandbox Code Playgroud)

然后将它们链接到您的main函数中.

func main() {
    http.Handler("/offers", validate(api1()))
    http.Handler("/getOffersList", validate(api2()))
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个回复很好,但我会通过指出验证器代码阻止错误链来更清楚 (2认同)