Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to get http response code in middle ware. #48

Closed
georgyo opened this issue Jul 6, 2014 · 2 comments
Closed

Unable to get http response code in middle ware. #48

georgyo opened this issue Jul 6, 2014 · 2 comments
Assignees
Labels

Comments

@georgyo
Copy link

georgyo commented Jul 6, 2014

If I wanted to create a simple logger to mimic apache access logs, it is currently impossible to get the written status code. http.ResponseWriter's implementation is http.response which is unexported. As such there is no way to get to it's also unexported http.response.status.

You can get the entire header map from http.ResponseWriter.Header() however it won't give you anything about the status because it never actually gets written to that map.

Mimicking apache access logs may not be ideal, but I will surely want to record the return code in some way.

Some (broken) sample code trying to implement a proper access_log logger.

 func Logger() gin.HandlerFunc {
    return func(c *gin.Context) {
        t := time.Now()
        ip, err := net.ResolveTCPAddr("tcp", c.Req.RemoteAddr)
        if err != nil {
            c.Abort(500)
        }

        // before request
        c.Next()
        // after request

        var user string
        if c.Req.URL.User != nil {
            user = c.Req.URL.User.Username()
        } else {
            user = "-"
        }

        latency := time.Since(t)
        statusCode := c.Writer.(*http.Response).StatusCode
        //statusCode := c.Writer.(*http.response).status
        log.Print(latency)
        fmt.Printf("%v - %v [%v] \"%v %v %v\" %v %v\n",
            ip.IP, user, t, c.Req.Method, c.Req.URL.Path,
            c.Req.Proto, statusCode, c.Req.ContentLength)
    }
}
@manucorporat
Copy link
Contributor

Hi! you should check out the develop branch: https://github.com/gin-gonic/gin/tree/develop
It brings tons of new features and performance improvements. #45

You can get the status code with: 'c.Writer.Status()' see logger.go in develop

@georgyo
Copy link
Author

georgyo commented Jul 7, 2014

Very cool! Keep up the great work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants