router_swapper.go 613 B

123456789101112131415161718192021222324252627282930
  1. package server
  2. import (
  3. "net/http"
  4. "sync"
  5. "github.com/gorilla/mux"
  6. )
  7. // routerSwapper is an http.Handler that allows you to swap
  8. // mux routers.
  9. type routerSwapper struct {
  10. mu sync.Mutex
  11. router *mux.Router
  12. }
  13. // Swap changes the old router with the new one.
  14. func (rs *routerSwapper) Swap(newRouter *mux.Router) {
  15. rs.mu.Lock()
  16. rs.router = newRouter
  17. rs.mu.Unlock()
  18. }
  19. // ServeHTTP makes the routerSwapper to implement the http.Handler interface.
  20. func (rs *routerSwapper) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  21. rs.mu.Lock()
  22. router := rs.router
  23. rs.mu.Unlock()
  24. router.ServeHTTP(w, r)
  25. }