How can I combine Go middleware pattern with error returning request handlers?

后端 未结 4 1929
青春惊慌失措
青春惊慌失措 2021-01-05 02:39

I am familiar with the Go middleware pattern like this:

// Pattern for writing HTTP middleware.
func middlewareHandler(next http.Handler) http.Handler {
             


        
4条回答
  •  醉梦人生
    2021-01-05 03:45

    From what I understand you wanted to chain your errorHandler function and and combine them in your loggingHandler.

    One way to do this is using a struct passing it to your loggingHandler as parameter like this :

    func loggingHandler(errorHandler ErrorHandler, next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            // Call your error handler to do thing
            err := errorHandler.ServeHTTP()
            if err != nil {
                log.Panic(err)
            }
    
            // next you can do what you want if error is nil.
            log.Printf("Strated %s %s", r.Method, r.URL.Path)
            next.ServeHTTP(w, r)
            // After executing the handler.
            log.Printf("Completed %s in %v", r.URL.Path, time.Since(start))
        })
    }
    
    // create the struct that has error handler
    type ErrorHandler struct {
    }
    
    // I return nil for the sake of example.
    func (e ErrorHandler) ServeHTTP() error {
        return nil
    }
    

    and in the main you call it like this :

    func main() {
        port := "8080"
        // you can pass any field to the struct. right now it is empty.
        errorHandler := ErrorHandler{}
    
        // and pass the struct to your loggingHandler.
        http.Handle("/", loggingHandler(errorHandler, http.HandlerFunc(index)))
    
    
        log.Println("App started on port = ", port)
        err := http.ListenAndServe(":"+port, nil)
        if err != nil {
            log.Panic("App Failed to start on = ", port, " Error : ", err.Error())
        }
    
    }
    

提交回复
热议问题