feat: impl requests handllers for contacts and healthcheck
This commit is contained in:
47
internal/handler/base_handler.go
Normal file
47
internal/handler/base_handler.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Route struct {
|
||||
pattern string
|
||||
handler func(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
|
||||
type baseHandler struct {
|
||||
mux *http.ServeMux
|
||||
registeredRoutes map[string]bool
|
||||
Routes []Route
|
||||
}
|
||||
|
||||
var (
|
||||
bh *baseHandler
|
||||
bhOnce sync.Once
|
||||
bhMu sync.RWMutex
|
||||
)
|
||||
|
||||
func NewBaseHandler(mux *http.ServeMux, routes []Route) *baseHandler {
|
||||
bhOnce.Do(func() {
|
||||
bh = &baseHandler{
|
||||
mux: mux,
|
||||
registeredRoutes: make(map[string]bool),
|
||||
Routes: routes,
|
||||
}
|
||||
})
|
||||
|
||||
bhMu.Lock()
|
||||
defer bhMu.Unlock()
|
||||
bh.registerRoutes(routes)
|
||||
return bh
|
||||
}
|
||||
|
||||
func (b *baseHandler) registerRoutes(routes []Route) {
|
||||
for _, route := range routes {
|
||||
if !bh.registeredRoutes[route.pattern] {
|
||||
b.mux.HandleFunc(route.pattern, route.handler)
|
||||
bh.registeredRoutes[route.pattern] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user