Author: Pedro Lucas Porcellis <porcellis@eletrotupi.com>
all: use a data dir as a reference to lookup the json contents
main.go | 32 +++++++++++++++++++-------------
diff --git a/main.go b/main.go index 0abe7e1850b9733f03474d409ffd18234a5e65ec..8a7c4d808030cb90966883d8a852b2e09120906c 100644 --- a/main.go +++ b/main.go @@ -22,9 +22,10 @@ return false } -func registerDomains(router chi.Router) { +func registerDomains(router chi.Router, dataDir string) { + jsonPath := dataDir + "/domains.json" router.Get("/domains", func(w http.ResponseWriter, r *http.Request) { - jsonFile, err := os.Open("data/domains.json") + jsonFile, err := os.Open(jsonPath) if err != nil { w.WriteHeader(500) @@ -33,9 +34,7 @@ return } - // defer the closing of our jsonFile so that we can parse it later on defer jsonFile.Close() - byteValue, _ := ioutil.ReadAll(jsonFile) w.Header().Add("Content-Type", "application/json; charset=utf-8") @@ -46,7 +45,7 @@ router.Get("/domains/*", func(w http.ResponseWriter, r *http.Request) { domain := chi.URLParam(r, "*") - jsonFile, err := os.Open("data/domains.json") + jsonFile, err := os.Open(jsonPath) if err != nil { w.WriteHeader(500) @@ -72,9 +71,11 @@ } }) } -func registerUsernames(router chi.Router) { +func registerUsernames(router chi.Router, dataDir string) { + jsonPath := dataDir + "/usernames.json" + router.Get("/usernames", func(w http.ResponseWriter, r *http.Request) { - jsonFile, err := os.Open("data/usernames.json") + jsonFile, err := os.Open(jsonPath) if err != nil { w.WriteHeader(500) @@ -83,9 +84,7 @@ return } - // defer the closing of our jsonFile so that we can parse it later on defer jsonFile.Close() - byteValue, _ := ioutil.ReadAll(jsonFile) w.Header().Add("Content-Type", "application/json; charset=utf-8") @@ -96,7 +95,7 @@ router.Get("/usernames/*", func(w http.ResponseWriter, r *http.Request) { domain := chi.URLParam(r, "*") - jsonFile, err := os.Open("data/usernames.json") + jsonFile, err := os.Open(jsonPath) if err != nil { w.WriteHeader(500) @@ -133,13 +132,20 @@ router.Use(middleware.RealIP) router.Use(middleware.Logger) - registerDomains(router) - registerUsernames(router) - addr := ":8121" if len(os.Args) > 2 { addr = os.Args[2] } + + dataDir := os.Getenv("ANTISPAM_DATADIR") + if dataDir == "" { + dataDir = "/usr/share/antispam-api/data" + } + + // TODO: Refactor the content of those two methods + // because they are identical + registerDomains(router, dataDir) + registerUsernames(router, dataDir) log.Printf("Listening on %s", addr) http.ListenAndServe(addr, router)