pauseable_handler.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2015 The etcd Authors
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package testutil
  15. import (
  16. "net/http"
  17. "sync"
  18. )
  19. type PauseableHandler struct {
  20. Next http.Handler
  21. mu sync.Mutex
  22. paused bool
  23. }
  24. func (ph *PauseableHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  25. ph.mu.Lock()
  26. paused := ph.paused
  27. ph.mu.Unlock()
  28. if !paused {
  29. ph.Next.ServeHTTP(w, r)
  30. } else {
  31. hj, ok := w.(http.Hijacker)
  32. if !ok {
  33. panic("webserver doesn't support hijacking")
  34. }
  35. conn, _, err := hj.Hijack()
  36. if err != nil {
  37. panic(err.Error())
  38. }
  39. conn.Close()
  40. }
  41. }
  42. func (ph *PauseableHandler) Pause() {
  43. ph.mu.Lock()
  44. defer ph.mu.Unlock()
  45. ph.paused = true
  46. }
  47. func (ph *PauseableHandler) Resume() {
  48. ph.mu.Lock()
  49. defer ph.mu.Unlock()
  50. ph.paused = false
  51. }