大猩猩复用器,“捕获"响应代码的最佳方法 [英] Gorilla mux, best way to 'catch' response codes

查看:129
本文介绍了大猩猩复用器,“捕获"响应代码的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用大猩猩多路复用器进行所有路由.现在我的应用程序运行良好,我想找到一种方法将我的所有响应代码记录到-例如-statds.我找到了这个包: https://godoc.org/github.com/gorilla/handlers#LoggingHandler

I'm using Gorilla mux for all my routing. Now my app is working fine, I want to find a way to log all my response codes to -for example- statds. I have found this package: https://godoc.org/github.com/gorilla/handlers#LoggingHandler

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

Which allows me to output all responses into apache format. Although this is nice, it's not 100% what I want. I just want to extract the response statusses and send them to statds. Now what's the best/easiest way to achieve this?

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)
}

上面的代码给了我这个

因此,我正在寻找类似的内容,但我希望能够使用响应代码执行某些操作",而不是将Apache访问日志输出到stdout.我还创建了一个包含我的示例代码的简单回购.您可以在此处找到它.

So I'm looking for something similar, but instead of outputting the Apache access logs to stdout, I would like to be able to "do something" with the response code. I have also created a simple repo which contains my sample code. You can find it here.

推荐答案

我发现这篇有用的博客文章来自蒂姆·安德森(Tim Andersson). 首先,他构建了一个满足该接口的新结构:

I found this useful Blog post from Tim Andersson. First he builds a new struct that satisfies the interface:

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)
}

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

Then he's using it as a wrapper (or middleware):

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))
    })
}

这篇关于大猩猩复用器,“捕获"响应代码的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆