Skip to content

Instantly share code, notes, and snippets.

@SteveBate
Created November 15, 2015 09:44
Show Gist options
  • Save SteveBate/b96bd3fd531f261aeede to your computer and use it in GitHub Desktop.
Save SteveBate/b96bd3fd531f261aeede to your computer and use it in GitHub Desktop.
Package response implements a ResponseWriter that captures additional info useful in logging scenarios
// Package response implements a ResponseWriter that captures additional info useful in logging scenarios
// such as response status code, request duration and a unique request id
package response
import (
"fmt"
"net/http"
"time"
// this is actually another gist (not go gettable)
"github.com/stevebate/uuid"
)
type LoggableResponse struct {
id uuid.UniqueId
method string
path string
proto string
status int
started time.Time
rw http.ResponseWriter
}
func NewLoggableResponse(rw http.ResponseWriter, req *http.Request) *LoggableResponse {
return &LoggableResponse{
id: uuid.NewUniqueId(),
method: req.Method,
path: req.URL.Path,
proto: req.Proto,
status: http.StatusOK,
started: time.Now(),
rw: rw,
}
}
func (l *LoggableResponse) Header() http.Header {
return l.rw.Header()
}
func (l *LoggableResponse) Write(data []byte) (int, error) {
return l.rw.Write(data)
}
func (l *LoggableResponse) WriteHeader(status int) {
l.status = status
l.rw.WriteHeader(status)
}
func (l *LoggableResponse) duration() string {
return time.Now().Sub(l.started).String()
}
func (l *LoggableResponse) LogStart() string {
return fmt.Sprintf("[-INFO] - %s - Id: %s, Method: %4s, Url: %20s, Protocol: %10s\n", time.Now().Format("2006-01-02 15:04:05"), l.id, l.method, l.path, l.proto)
}
func (l *LoggableResponse) LogEnd() string {
return fmt.Sprintf("[-INFO] - %s - Id: %s, Method: %4s, Url: %20s, Protocol: %10s, Duration: %10s, Status: %d\n", time.Now().Format("2006-01-02 15:04:05"), l.id, l.method, l.path, l.proto, l.duration(), l.status)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment