pauseable_handler.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2015 CoreOS, Inc.
  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. return
  35. }
  36. conn, _, err := hj.Hijack()
  37. if err != nil {
  38. panic(err.Error())
  39. return
  40. }
  41. conn.Close()
  42. }
  43. }
  44. func (ph *PauseableHandler) Pause() {
  45. ph.mu.Lock()
  46. defer ph.mu.Unlock()
  47. ph.paused = true
  48. }
  49. func (ph *PauseableHandler) Resume() {
  50. ph.mu.Lock()
  51. defer ph.mu.Unlock()
  52. ph.paused = false
  53. }