pauseable_handler.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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 testutil
  14. import (
  15. "net/http"
  16. "sync"
  17. )
  18. type PauseableHandler struct {
  19. Next http.Handler
  20. mu sync.Mutex
  21. paused bool
  22. }
  23. func (ph *PauseableHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  24. ph.mu.Lock()
  25. paused := ph.paused
  26. ph.mu.Unlock()
  27. if !paused {
  28. ph.Next.ServeHTTP(w, r)
  29. } else {
  30. hj, ok := w.(http.Hijacker)
  31. if !ok {
  32. panic("webserver doesn't support hijacking")
  33. return
  34. }
  35. conn, _, err := hj.Hijack()
  36. if err != nil {
  37. panic(err.Error())
  38. return
  39. }
  40. conn.Close()
  41. }
  42. }
  43. func (ph *PauseableHandler) Pause() {
  44. ph.mu.Lock()
  45. defer ph.mu.Unlock()
  46. ph.paused = true
  47. }
  48. func (ph *PauseableHandler) Resume() {
  49. ph.mu.Lock()
  50. defer ph.mu.Unlock()
  51. ph.paused = false
  52. }