diff --git a/http.go b/http.go index eefd6bf..bf73066 100644 --- a/http.go +++ b/http.go @@ -3,6 +3,8 @@ package main import ( "encoding/json" "fmt" + log "github.com/sirupsen/logrus" + "github.com/spf13/viper" "net" "net/http" "net/url" @@ -10,17 +12,17 @@ import ( "strings" ) -func statusRequest(w http.ResponseWriter, r *http.Request) { +func statusHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -func serversRequest(w http.ResponseWriter, r *http.Request) { +func mirrorsHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(servers) } -func redirectRequest(w http.ResponseWriter, r *http.Request) { +func redirectHandler(w http.ResponseWriter, r *http.Request) { ipStr, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { @@ -66,3 +68,22 @@ func redirectRequest(w http.ResponseWriter, r *http.Request) { w.Header().Set("Location", u.String()) w.WriteHeader(http.StatusFound) } + +func reloadHandler(w http.ResponseWriter, r *http.Request) { + if mapFile := viper.GetString("dl_map"); mapFile != "" { + log.WithField("file", mapFile).Info("Loading download map") + + newMap, err := loadMap(mapFile) + + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + dlMap = newMap + + return + } + + w.WriteHeader(http.StatusNotFound) +} diff --git a/main.go b/main.go index c8b2152..4d5b408 100644 --- a/main.go +++ b/main.go @@ -26,6 +26,8 @@ type City struct { } func main() { + viper.SetDefault("bind", ":8080") + viper.SetConfigName("dlrouter") // name of config file (without extension) viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name viper.AddConfigPath("/etc/dlrouter/") // path to look for the config file in @@ -119,9 +121,10 @@ func main() { mux := http.NewServeMux() - mux.HandleFunc("/status", RealIPMiddleware(statusRequest)) - mux.HandleFunc("/servers", RealIPMiddleware(serversRequest)) - mux.HandleFunc("/", RealIPMiddleware(redirectRequest)) + mux.HandleFunc("/status", statusHandler) + mux.HandleFunc("/mirrors", mirrorsHandler) + mux.HandleFunc("/reload", reloadHandler) + mux.HandleFunc("/", RealIPMiddleware(redirectHandler)) - http.ListenAndServe(":8080", mux) + http.ListenAndServe(viper.GetString("bind"), mux) }