Skip to content

Instantly share code, notes, and snippets.

@inspirit941
Created October 25, 2024 03:15
Show Gist options
  • Save inspirit941/3afc8c2fa91767b4a2c47d2a271643b6 to your computer and use it in GitHub Desktop.
Save inspirit941/3afc8c2fa91767b4a2c47d2a271643b6 to your computer and use it in GitHub Desktop.
// ServeHTTP implements http.Handler.
func (h *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Path-based dispatch
h.routersMu.RLock()
keyedHandler, ok := h.routers[r.URL.Path]
h.routersMu.RUnlock()
if ok {
// Check if source still exists.
_, err := h.lister.GitHubSources(keyedHandler.namespace).Get(keyedHandler.name)
if err == nil {
keyedHandler.handler.ServeHTTP(w, r)
return
}
h.Unregister(r.URL.Path)
}
http.NotFoundHandler().ServeHTTP(w, r)
}
// Register adds a new GitHub event handler for the given GitHubSource.
func (h *Router) Register(name, namespace, path string, handler http.Handler) {
h.routersMu.Lock()
defer h.routersMu.Unlock()
h.routers[path] = keyedHandler{
handler: handler,
namespace: namespace,
name: name,
}
}
// Unregister removes the GitHubSource served at the given path.
func (h *Router) Unregister(path string) {
h.routersMu.Lock()
defer h.routersMu.Unlock()
delete(h.routers, path)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment