traefik/pkg/middlewares/handler_switcher.go

36 lines
948 B
Go
Raw Normal View History

package middlewares
import (
"net/http"
2023-02-03 14:24:05 +00:00
"github.com/traefik/traefik/v3/pkg/safe"
)
2020-05-11 10:06:07 +00:00
// HTTPHandlerSwitcher allows hot switching of http.ServeMux.
type HTTPHandlerSwitcher struct {
handler *safe.Safe
}
2020-05-11 10:06:07 +00:00
// NewHandlerSwitcher builds a new instance of HTTPHandlerSwitcher.
func NewHandlerSwitcher(newHandler http.Handler) (hs *HTTPHandlerSwitcher) {
return &HTTPHandlerSwitcher{
handler: safe.New(newHandler),
}
}
func (h *HTTPHandlerSwitcher) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
2018-11-14 09:18:03 +00:00
handlerBackup := h.handler.Get().(http.Handler)
handlerBackup.ServeHTTP(rw, req)
}
2020-05-11 10:06:07 +00:00
// GetHandler returns the current http.ServeMux.
func (h *HTTPHandlerSwitcher) GetHandler() (newHandler http.Handler) {
2018-11-14 09:18:03 +00:00
handler := h.handler.Get().(http.Handler)
return handler
}
2020-05-11 10:06:07 +00:00
// UpdateHandler safely updates the current http.ServeMux with a new one.
func (h *HTTPHandlerSwitcher) UpdateHandler(newHandler http.Handler) {
2018-11-14 09:18:03 +00:00
h.handler.Set(newHandler)
}