debug.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package middleware
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "io"
  6. "net/http"
  7. "github.com/Sirupsen/logrus"
  8. "github.com/docker/docker/api/server/httputils"
  9. "github.com/docker/docker/pkg/ioutils"
  10. "golang.org/x/net/context"
  11. )
  12. // DebugRequestMiddleware dumps the request to logger
  13. func DebugRequestMiddleware(handler httputils.APIFunc) httputils.APIFunc {
  14. return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  15. logrus.Debugf("%s %s", r.Method, r.RequestURI)
  16. if r.Method != "POST" {
  17. return handler(ctx, w, r, vars)
  18. }
  19. if err := httputils.CheckForJSON(r); err != nil {
  20. return handler(ctx, w, r, vars)
  21. }
  22. maxBodySize := 4096 // 4KB
  23. if r.ContentLength > int64(maxBodySize) {
  24. return handler(ctx, w, r, vars)
  25. }
  26. body := r.Body
  27. bufReader := bufio.NewReaderSize(body, maxBodySize)
  28. r.Body = ioutils.NewReadCloserWrapper(bufReader, func() error { return body.Close() })
  29. b, err := bufReader.Peek(maxBodySize)
  30. if err != io.EOF {
  31. // either there was an error reading, or the buffer is full (in which case the request is too large)
  32. return handler(ctx, w, r, vars)
  33. }
  34. var postForm map[string]interface{}
  35. if err := json.Unmarshal(b, &postForm); err == nil {
  36. if _, exists := postForm["password"]; exists {
  37. postForm["password"] = "*****"
  38. }
  39. formStr, errMarshal := json.Marshal(postForm)
  40. if errMarshal == nil {
  41. logrus.Debugf("form data: %s", string(formStr))
  42. } else {
  43. logrus.Debugf("form data: %q", postForm)
  44. }
  45. }
  46. return handler(ctx, w, r, vars)
  47. }
  48. }