logger.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package logger
  2. import (
  3. "log"
  4. "net/http"
  5. "strings"
  6. "time"
  7. )
  8. type ResponseWriter struct {
  9. http.ResponseWriter
  10. Status int
  11. }
  12. func (r *ResponseWriter) WriteHeader(status int) {
  13. r.Status = status
  14. r.ResponseWriter.WriteHeader(status)
  15. }
  16. func ClientIP(r *http.Request) string {
  17. ips := ClientIPs(r)
  18. if len(ips) >= 1 {
  19. return ips[0]
  20. }
  21. return ""
  22. }
  23. func ClientIPs(r *http.Request) []string {
  24. ra := r.RemoteAddr
  25. if xff := strings.Trim(r.Header.Get("X-Forwarded-For"), " "); xff != "" {
  26. ra = strings.Join([]string{xff, ra}, ",")
  27. }
  28. res := []string{}
  29. ips := strings.Split(ra, ",")
  30. for _, ip := range ips {
  31. res = append(res, strings.Trim(ip, " "))
  32. }
  33. return res
  34. }
  35. func LogRequests(handler http.Handler) http.Handler {
  36. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  37. start := time.Now()
  38. nw := &ResponseWriter{
  39. ResponseWriter: w,
  40. Status: http.StatusOK,
  41. }
  42. handler.ServeHTTP(nw, r)
  43. duration := time.Since(start)
  44. log.Printf(
  45. "\"%s\" \"%s %s\" %d \"%.3f ms\"\n",
  46. ClientIP(r), r.Method, r.URL, nw.Status, duration.Seconds(),
  47. )
  48. })
  49. }