From 75077ed8efe225a0bb430007b4c7c6fffb6584eb Mon Sep 17 00:00:00 2001 From: yair-voca <62960726+yair-voca@users.noreply.github.com> Date: Tue, 12 May 2020 19:54:08 +0300 Subject: [PATCH] Added new ServeHTTP end point for fetching dispatcher set (#5) --- main.go | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index 1fa6767..ab8cc5a 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,7 @@ package main import ( "context" + "encoding/json" "flag" "fmt" "io" @@ -156,7 +157,7 @@ func (s *dispatcherSets) maintain(ctx context.Context) error { return ctx.Err() } -// ServeHTTP offers a web service by which clients may validate membership of an IP address within a dispatcher set +// ServeHTTP offers a web service by which clients may validate membership of an IP address within a dispatcher set or fetch a dispatcher set func (s *dispatcherSets) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Handle requests for /check// to validate membership of an IP to a dispatcher set if strings.HasPrefix(r.URL.Path, "/check/") { @@ -176,6 +177,27 @@ func (s *dispatcherSets) ServeHTTP(w http.ResponseWriter, r *http.Request) { } w.WriteHeader(http.StatusNotFound) return + } else if strings.HasPrefix(r.URL.Path, "/dispatcher/") { // Handle requests for /dispatcher/ to fetch a dispatcher set + pieces := strings.Split(strings.TrimPrefix(r.URL.Path, "/dispatcher/"), "/") + if len(pieces) != 1 { + w.WriteHeader(http.StatusBadRequest) + return + } + setID, err := strconv.Atoi(pieces[0]) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + selectedSet := s.getDispatcherSet(setID) + if selectedSet != nil { + js, err := json.Marshal(selectedSet) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Write(js) //If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) before writing the data + return + } } w.WriteHeader(http.StatusNotFound) @@ -189,6 +211,14 @@ func (s *dispatcherSets) validateSetMember(id int, addr string) bool { return selectedSet.Validate(addr) } +func (s *dispatcherSets) getDispatcherSet(id int) sets.DispatcherSet { + selectedSet, ok := s.sets[id] + if !ok { + return nil + } + return selectedSet +} + // notify signals to kamailio to reload its dispatcher list func (s *dispatcherSets) notify() error { return binrpc.InvokeMethod("dispatcher.reload", s.rpcHost, s.rpcPort) @@ -268,7 +298,7 @@ func run() error { } }) - // Run a web service to offer IP checks for each member of the dispatcher set + // Run a web service to offer IP checks for each member of the dispatcher set and fetch a dispatcher set if apiAddr != "" { var srv http.Server srv.Addr = apiAddr