Skip to content

Commit

Permalink
Added new ServeHTTP end point for fetching dispatcher set (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
yair-voca authored May 12, 2020
1 parent d199e5e commit 75077ed
Showing 1 changed file with 32 additions and 2 deletions.
34 changes: 32 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
Expand Down Expand Up @@ -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/<setID>/<ip address> to validate membership of an IP to a dispatcher set
if strings.HasPrefix(r.URL.Path, "/check/") {
Expand All @@ -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/<setID> 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)
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 75077ed

Please sign in to comment.