debug.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. Copyright (c) 2014 VMware, Inc. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package debug
  14. import (
  15. "io"
  16. "regexp"
  17. )
  18. // Provider specified the interface types must implement to be used as a
  19. // debugging sink. Having multiple such sink implementations allows it to be
  20. // changed externally (for example when running tests).
  21. type Provider interface {
  22. NewFile(s string) io.WriteCloser
  23. Flush()
  24. }
  25. // ReadCloser is a struct that satisfies the io.ReadCloser interface
  26. type ReadCloser struct {
  27. io.Reader
  28. io.Closer
  29. }
  30. // NewTeeReader wraps io.TeeReader and patches through the Close() function.
  31. func NewTeeReader(rc io.ReadCloser, w io.Writer) io.ReadCloser {
  32. return ReadCloser{
  33. Reader: io.TeeReader(rc, w),
  34. Closer: rc,
  35. }
  36. }
  37. var currentProvider Provider = nil
  38. var scrubPassword = regexp.MustCompile(`<password>(.*)</password>`)
  39. func SetProvider(p Provider) {
  40. if currentProvider != nil {
  41. currentProvider.Flush()
  42. }
  43. currentProvider = p
  44. }
  45. // Enabled returns whether debugging is enabled or not.
  46. func Enabled() bool {
  47. return currentProvider != nil
  48. }
  49. // NewFile dispatches to the current provider's NewFile function.
  50. func NewFile(s string) io.WriteCloser {
  51. return currentProvider.NewFile(s)
  52. }
  53. // Flush dispatches to the current provider's Flush function.
  54. func Flush() {
  55. currentProvider.Flush()
  56. }
  57. func Scrub(in []byte) []byte {
  58. return scrubPassword.ReplaceAll(in, []byte(`<password>********</password>`))
  59. }