Gorilla mux,“捕获”响应代码的最佳方式

Rog*_*ers 5 http go mux gorilla

我所有的路由都使用 Gorilla mux。现在我的应用程序工作正常,我想找到一种方法将我的所有响应代码记录到 - 例如 - statds。我找到了这个包:https ://godoc.org/github.com/gorilla/handlers#LoggingHandler

这允许我将所有响应输出为 apache 格式。虽然这很好,但这并不是 100% 我想要的。我只想将extract响应状态发送到 statds。现在实现这一目标的最佳/最简单方法是什么?

package main

import (
    "log"
    "net/http"
    "os"

    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
    "github.com/rogierlommers/mux-status-handler/articles"
    "github.com/rogierlommers/mux-status-handler/users"
)

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/products", articles.Handler)
    r.HandleFunc("/users", users.Handler)

    loggedRouter := handlers.LoggingHandler(os.Stdout, r)
    log.Println("listening on 8080")
    http.ListenAndServe(":8080", loggedRouter)
}
Run Code Online (Sandbox Code Playgroud)

上面的代码给了我这个:

Apache 日志格式输出

所以我正在寻找类似的东西,但我不希望将 Apache 访问日志输出到 stdout,而是希望能够使用响应代码“做某事”。我还创建了一个简单的存储库,其中包含我的示例代码。你可以在这里找到它。

小智 7

我发现蒂姆·安德森这篇有用的博客文章。首先,他构建了一个满足接口的新结构:

type loggingResponseWriter struct {
    http.ResponseWriter
    statusCode int
}

func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
    return &loggingResponseWriter{w, http.StatusOK}
}

func (lrw *loggingResponseWriter) WriteHeader(code int) {
    lrw.statusCode = code
    lrw.ResponseWriter.WriteHeader(code)
}
Run Code Online (Sandbox Code Playgroud)

然后他将其用作包装器(或中间件):

func wrapHandlerWithLogging(wrappedHandler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
        log.Printf("--> %s %s", req.Method, req.URL.Path)

        lrw := NewLoggingResponseWriter(w)
        wrappedHandler.ServeHTTP(lrw, req)

        statusCode := lrw.statusCode
        log.Printf("<-- %d %s", statusCode, http.StatusText(statusCode))
    })
}
Run Code Online (Sandbox Code Playgroud)


nba*_*ari 0

这就是如何使用violetear制作它,可能可以给您有关如何处理处理程序中的状态代码的提示:

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/nbari/violetear"
)

func handleGET(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("I handle GET requests\n"))
    // do anything here with the Status code
    cw := w.(*violetear.ResponseWriter)
    fmt.Printf("The status code is: %d\n", cw.Status())
}

func main() {
    router := violetear.New()
    router.HandleFunc("/", handleGET, "GET")
    log.Fatal(http.ListenAndServe(":8080", router))
}
Run Code Online (Sandbox Code Playgroud)

通过使用:

cw := w.(*violetear.ResponseWriter)
Run Code Online (Sandbox Code Playgroud)

您可以访问violetear.ResponseWriter,它通过使用公开状态代码cw.Status()