/Godeps/_workspace/src/github.com/jpillora/requestlog/wrap.go

https://gitlab.com/alidzapp/cloud-torrent · Go · 87 lines · 75 code · 12 blank · 0 comment · 12 complexity · 14372f390ab87aac06b7e989215df7d9 MD5 · raw file

  1. package requestlog
  2. import (
  3. "io"
  4. "net/http"
  5. "os"
  6. "regexp"
  7. "text/template"
  8. "time"
  9. "github.com/andrew-d/go-termutil"
  10. "github.com/jpillora/ansi"
  11. "github.com/jpillora/sizestr"
  12. )
  13. func init() {
  14. sizestr.LowerCase()
  15. }
  16. type Colors struct {
  17. Grey, Green, Cyan, Yellow, Red, Reset string
  18. }
  19. var basicColors = &Colors{string(ansi.ResetBytes), string(ansi.GreenBytes), string(ansi.CyanBytes), string(ansi.YellowBytes), string(ansi.YellowBytes), string(ansi.ResetBytes)}
  20. var noColors = &Colors{} //no colors
  21. type Options struct {
  22. Writer io.Writer
  23. TimeFormat string
  24. Format string
  25. formatTmpl *template.Template
  26. Colors *Colors
  27. }
  28. var DefaultOptions = Options{
  29. Writer: os.Stdout,
  30. TimeFormat: "2006/01/02 15:04:05.000",
  31. Format: `{{ if .Timestamp }}{{ .Timestamp }} {{end}}` +
  32. `{{ .Method }} {{ .Path }} {{ .CodeColor }}{{ .Code }}{{ .Reset }} ` +
  33. `{{ .Duration }}{{ if .Size }} {{ .Size }}{{end}}` +
  34. `{{ if .IP }} ({{ .IP }}){{end}}` + "\n",
  35. Colors: defaultColors(),
  36. }
  37. func defaultColors() *Colors {
  38. sizestr.ToggleCase()
  39. if termutil.Isatty(os.Stdout.Fd()) {
  40. return basicColors
  41. } else {
  42. return noColors
  43. }
  44. }
  45. func Wrap(next http.Handler) http.Handler {
  46. return WrapWith(next, Options{})
  47. }
  48. func WrapWith(next http.Handler, opts Options) http.Handler {
  49. if opts.Writer == nil {
  50. opts.Writer = DefaultOptions.Writer
  51. }
  52. if opts.TimeFormat == "" {
  53. opts.TimeFormat = DefaultOptions.TimeFormat
  54. }
  55. if opts.Format == "" {
  56. opts.Format = DefaultOptions.Format
  57. }
  58. if opts.Colors == nil {
  59. opts.Colors = DefaultOptions.Colors
  60. }
  61. var err error
  62. opts.formatTmpl, err = template.New("format").Parse(opts.Format)
  63. if err != nil {
  64. panic(err)
  65. }
  66. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  67. m := monitorWriter(w, r, &opts)
  68. next.ServeHTTP(m, r)
  69. m.Log()
  70. })
  71. }
  72. var fmtDurationRe = regexp.MustCompile(`\.\d+`)
  73. func fmtDuration(t time.Duration) string {
  74. return fmtDurationRe.ReplaceAllString(t.String(), "")
  75. }