From 737e4268fcf23312d404399980b0a05031e0da3a Mon Sep 17 00:00:00 2001 From: Stefan Hoffmann Date: Sat, 6 Feb 2021 22:32:24 +0100 Subject: [PATCH 1/6] added first support for config file --- example.config.json | 15 ++++++ main.go | 126 ++++++++++++++++---------------------------- types.go | 48 +++++++++++++++++ 3 files changed, 109 insertions(+), 80 deletions(-) create mode 100644 example.config.json diff --git a/example.config.json b/example.config.json new file mode 100644 index 0000000..2a300a8 --- /dev/null +++ b/example.config.json @@ -0,0 +1,15 @@ +{ + "unms": { + "active": "true", + "unmsAPIUrl": "https://unifi.freifunk-troisdorf.de/v2.1", + "APItoken": "API TOKEN", + "devicesURL": "https://git.freifunk-rhein-sieg.net/Freifunk-Troisdorf/ubnt-freifunk-map-api/raw/branch/master/" + }, + "unifi": { + "active": "true", + "APIUrl": "https://unifi.freifunk-troisdorf.de:8443", + "user": "APIuser", + "password": "PASSWORD", + "ucDevicesURL": "https://git.freifunk-rhein-sieg.net/Freifunk-Troisdorf/ubnt-freifunk-map-api/raw/branch/master/" + } +} \ No newline at end of file diff --git a/main.go b/main.go index 8c82485..74b9baa 100644 --- a/main.go +++ b/main.go @@ -10,6 +10,7 @@ import ( "log" "net/http" "net/http/cookiejar" + "os" "strconv" "strings" "time" @@ -17,74 +18,41 @@ import ( _ "git.nils.zone/nils/prettify" ) -// types - const ( - baseURL = "https://unifi.freifunk-troisdorf.de/v2.1" - ucBaseURL = "https://unifi.freifunk-troisdorf.de:8443" - iso8601 = "2006-01-02T15:04:05-0700" + iso8601 = "2006-01-02T15:04:05-0700" ) // flags -var token = flag.String("token", "", "Defines the x-auth-token") -var ucUser = flag.String("ucUser", "", "Defines the Unifi API User") -var ucPass = flag.String("ucPass", "", "Defines the Unifi API Password") +var configPath = flag.String("configPath", "config.json", "Path to config.json") var version = "development" -var delay time.Duration = 60 * time.Second +var delay time.Duration = 5 * time.Second func main() { log.Printf("starting version %s...\n", version) // parse all flags flag.Parse() + c := loadConfig(*configPath) // check if flags are set - if *token == "" { - log.Fatalln("Please specify an API token via the flag '-token'") + if *configPath == "" { + log.Fatalln("Please specify path to config.json flag '-configPath'") } - if *ucPass == "" { - log.Fatalln("Please specify an API Password via the flag '-ucPass'") - } - if *ucUser == "" { - log.Fatalln("Please specify an API User via the flag '-ucUser'") - } - // start API processing (runs in a loop) - go processAPIs() + go processAPIs(c) // start webserver on Port 3000 serveJSON() } -//switch Unifi AP Mod IDs to Names -func lookupModels(model string) string { - switch model { - case "BZ2", "U2S48", "U2Sv2": - return "Unifi AP" - case "BZ2LR", "U2L48", "U2Lv2": - return "UniFi AP-LR" - case "U7E", "U7Ev2": - return "UniFi AP-AC" - case "U7HD", "U7SHD": - return "UniFi AP-HD" - case "UXSDM": - return "UniFi AP-BaseStationXG" - case "UCMSH": - return "AP-MeshXG" - case "U7MP": - return "AP-AC-Mesh-Pro" - case "U7LR": - return "UniFi AP-AC-LR" - case "U7LT": - return "UniFi AP-AC-Lite" - case "U7P": - return "UniFi AP-Pro" - case "U7MSH": - return "UniFi AP-AC-Mesh" - case "U7PG2": - return "UniFi AP-AC-Pro" - default: - return "Unifi Gerät" +func loadConfig(file string) Config { + var config Config + configFile, err := os.Open(file) + if err != nil { + log.Fatalln(err) } + jsonParse := json.NewDecoder(configFile) + jsonParse.Decode(&config) + return config } //int to bool converter @@ -96,27 +64,27 @@ func itob(i int) bool { } //Unifi Controller API processing -func processUcAPIs() ([]node, []link) { +func processUcAPIs(c Config) ([]node, []link) { //get list of Unifi devices to display var nodes []node var links []link - d, err := getDevices("ucDevices.json") + d, err := getDevices(c, "ucDevices.json") if err != nil { log.Fatalln(err) } //call Unifi Controller - ucAPI := newAPI(*ucUser, *ucPass, ucBaseURL) + ucAPI := newAPI(c.Unifi.User, c.Unifi.Password, c.Unifi.APIURL) //login ucAPI.ucLogin() //get all Sites from Controller sites, err := ucAPI.ucGetSites() if err != nil { - panic(err) + log.Fatalln(err) } //get all devices in all sites devices, err := ucAPI.ucGetDevices(sites) if err != nil { - panic(err) + log.Fatalln(err) } //build nodes struct @@ -135,11 +103,11 @@ func processUcAPIs() ([]node, []link) { load, err := strconv.ParseFloat(currentDevice.Sysstats.CPU, 64) if err != nil { - panic(err) + log.Fatalln(err) } mem, err := strconv.ParseFloat(currentDevice.Sysstats.Memory, 64) if err != nil { - panic(err) + log.Fatalln(err) } nodes = append(nodes, node{ @@ -180,12 +148,12 @@ func processUcAPIs() ([]node, []link) { } //UNMS API processing (Richtfunk) -func processUNMSAPI() ([]node, []link) { +func processUNMSAPI(c Config) ([]node, []link) { // Variables for runtime var links []link var nodes []node - d, err := getDevices("devices.json") + d, err := getDevices(c, "devices.json") if err != nil { log.Fatalln(err) } @@ -193,7 +161,7 @@ func processUNMSAPI() ([]node, []link) { // API CALL 1 log.Println("calling API 1") var u []unifiAPIResponse - err = callUnifiAPI("/devices", &u) + err = callUnifiAPI(c, "/devices", &u) if err != nil { log.Fatalln(err) } @@ -217,13 +185,13 @@ func processUNMSAPI() ([]node, []link) { // API CALL 2 log.Println("calling API 2 for device", d.Devices[i].Name) var details unifiAPIDetails - callUnifiAPI("/devices/erouters/"+dev.Identification.ID, &details) + callUnifiAPI(c, "/devices/erouters/"+dev.Identification.ID, &details) // END OF API CALL 2 // API CALL 3 log.Println("calling API 3 for device", d.Devices[i].Name) var airmaxes []unifiAPIAirmax - callUnifiAPI("/devices/airmaxes/"+dev.Identification.ID+"/stations", &airmaxes) + callUnifiAPI(c, "/devices/airmaxes/"+dev.Identification.ID+"/stations", &airmaxes) // check if remote mac address is part of our published network for i := range airmaxes { if isRemoteMACpublished(airmaxes[i].DeviceIdentification.MAC, d.Devices) == true { @@ -270,14 +238,14 @@ func processUNMSAPI() ([]node, []link) { return nodes, links } -func processAPIs() { +func processAPIs(c Config) { tick := time.Tick(delay) for range tick { var nodes []node var links []link - unmsNodes, unmsLinks := processUNMSAPI() - ucNodes, ucLinks := processUcAPIs() + unmsNodes, unmsLinks := processUNMSAPI(c) + ucNodes, ucLinks := processUcAPIs(c) nodes = append(nodes, unmsNodes...) nodes = append(nodes, ucNodes...) links = append(links, unmsLinks...) @@ -311,43 +279,41 @@ func getFile(url string) []byte { return byteValue } -func getDevices(file string) (devices, error) { +func getDevices(c Config, file string) (devices, error) { // get devices from JSON file - jsonFile := getFile("https://git.freifunk-rhein-sieg.net/Freifunk-Troisdorf/ubnt-freifunk-map-api/raw/branch/master/" + file) + jsonFile := getFile(c.Unms.DevicesURL + file) // read file to bytes // variable for d var d devices // unmarshal to struct - json.Unmarshal(jsonFile, &d) + err := json.Unmarshal(jsonFile, &d) + if err != nil { + fmt.Println("can´t get devices file from " + c.Unms.DevicesURL) + log.Fatal(err) + } return d, nil } -func callUnifiAPI(url string, i interface{}) error { - request, err := http.NewRequest(http.MethodGet, baseURL+url, nil) +func callUnifiAPI(c Config, url string, i interface{}) error { + request, err := http.NewRequest(http.MethodGet, c.Unms.UnmsAPIURL+url, nil) if err != nil { - return errors.New(fmt.Sprint("can't set request", baseURL+url)) + return errors.New(fmt.Sprint("can't set request", c.Unms.UnmsAPIURL+url)) } - request.Header.Set("x-auth-token", *token) + request.Header.Set("x-auth-token", c.Unms.APItoken) client := &http.Client{} response, err := client.Do(request) if err != nil { - return fmt.Errorf("can't get request %s with x-auth-token %s", baseURL+url, *token) + return fmt.Errorf("can't get request %s with x-auth-token %s", c.Unms.UnmsAPIURL+url, c.Unms.APItoken) + } + if response.StatusCode != 200 { + log.Fatalln("Can´t call UNMS API, check token and URL. HTTP Status: ", response.StatusCode) } - data, err := ioutil.ReadAll(response.Body) defer response.Body.Close() if err != nil { return fmt.Errorf("can't read response body: %+v", response.Body) } - // try to fetch errors - var a apiResponse - json.Unmarshal(data, &a) - - if a.StatusCode != 0 { - return fmt.Errorf("got following errorcode from API: %d %s %s", a.StatusCode, a.Error, a.Message) - } - // no error occurred, unmarshal to struct json.Unmarshal(data, &i) return nil diff --git a/types.go b/types.go index 069e28c..c152b25 100644 --- a/types.go +++ b/types.go @@ -10,6 +10,22 @@ import ( "time" ) +type Config struct { + Unms struct { + Active string `json:"active"` + UnmsAPIURL string `json:"unmsAPIUrl"` + APItoken string `json:"APItoken"` + DevicesURL string `json:"devicesURL"` + } `json:"unms"` + Unifi struct { + Active string `json:"active"` + APIURL string `json:"APIUrl"` + User string `json:"user"` + Password string `json:"password"` + UCDevicesURL string `json:"ucDevicesURL"` + } `json:"unifi"` +} + type device struct { Name string `json:"name"` MAC string `json:"mac"` @@ -178,3 +194,35 @@ type ucAPIData struct { baseURL string client *http.Client } + +//switch Unifi AP Mod IDs to Names +func lookupModels(model string) string { + switch model { + case "BZ2", "U2S48", "U2Sv2": + return "Unifi AP" + case "BZ2LR", "U2L48", "U2Lv2": + return "UniFi AP-LR" + case "U7E", "U7Ev2": + return "UniFi AP-AC" + case "U7HD", "U7SHD": + return "UniFi AP-HD" + case "UXSDM": + return "UniFi AP-BaseStationXG" + case "UCMSH": + return "AP-MeshXG" + case "U7MP": + return "AP-AC-Mesh-Pro" + case "U7LR": + return "UniFi AP-AC-LR" + case "U7LT": + return "UniFi AP-AC-Lite" + case "U7P": + return "UniFi AP-Pro" + case "U7MSH": + return "UniFi AP-AC-Mesh" + case "U7PG2": + return "UniFi AP-AC-Pro" + default: + return "Unifi Gerät" + } +} From a1bb1282914a3b64b23c3c01bfb1511911969583 Mon Sep 17 00:00:00 2001 From: Stefan Hoffmann Date: Sat, 6 Feb 2021 22:44:05 +0100 Subject: [PATCH 2/6] fixed devices url --- main.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 74b9baa..e698925 100644 --- a/main.go +++ b/main.go @@ -68,7 +68,7 @@ func processUcAPIs(c Config) ([]node, []link) { //get list of Unifi devices to display var nodes []node var links []link - d, err := getDevices(c, "ucDevices.json") + d, err := getDevices(c.Unifi.UCDevicesURL) if err != nil { log.Fatalln(err) } @@ -153,7 +153,7 @@ func processUNMSAPI(c Config) ([]node, []link) { var links []link var nodes []node - d, err := getDevices(c, "devices.json") + d, err := getDevices(c.Unms.DevicesURL) if err != nil { log.Fatalln(err) } @@ -279,9 +279,9 @@ func getFile(url string) []byte { return byteValue } -func getDevices(c Config, file string) (devices, error) { +func getDevices(url string) (devices, error) { // get devices from JSON file - jsonFile := getFile(c.Unms.DevicesURL + file) + jsonFile := getFile(url) // read file to bytes // variable for d @@ -289,7 +289,7 @@ func getDevices(c Config, file string) (devices, error) { // unmarshal to struct err := json.Unmarshal(jsonFile, &d) if err != nil { - fmt.Println("can´t get devices file from " + c.Unms.DevicesURL) + fmt.Println("can´t get devices file from " + url) log.Fatal(err) } return d, nil From e133a1e95d386ea7f4c8a7b029043415b9099fa9 Mon Sep 17 00:00:00 2001 From: Stefan Hoffmann Date: Sat, 6 Feb 2021 22:45:10 +0100 Subject: [PATCH 3/6] Ignore config files! --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 1938740..09f1d9e 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,4 @@ output/* ubnt-freifunk-map-api +config.json From 861d1c5d5ebe6eead05df4d5307e26a4fc1cac77 Mon Sep 17 00:00:00 2001 From: Stefan Hoffmann Date: Sun, 7 Feb 2021 10:46:39 +0100 Subject: [PATCH 4/6] Added enbled flag to APIs in config file --- example.config.json | 4 ++-- main.go | 32 ++++++++++++++++++-------------- types.go | 6 +++--- 3 files changed, 23 insertions(+), 19 deletions(-) diff --git a/example.config.json b/example.config.json index 2a300a8..ca7db0b 100644 --- a/example.config.json +++ b/example.config.json @@ -1,12 +1,12 @@ { "unms": { - "active": "true", + "enabled": true, "unmsAPIUrl": "https://unifi.freifunk-troisdorf.de/v2.1", "APItoken": "API TOKEN", "devicesURL": "https://git.freifunk-rhein-sieg.net/Freifunk-Troisdorf/ubnt-freifunk-map-api/raw/branch/master/" }, "unifi": { - "active": "true", + "enabled": true, "APIUrl": "https://unifi.freifunk-troisdorf.de:8443", "user": "APIuser", "password": "PASSWORD", diff --git a/main.go b/main.go index e698925..dc69628 100644 --- a/main.go +++ b/main.go @@ -25,13 +25,13 @@ const ( // flags var configPath = flag.String("configPath", "config.json", "Path to config.json") var version = "development" -var delay time.Duration = 5 * time.Second +var delay time.Duration = 60 * time.Second func main() { log.Printf("starting version %s...\n", version) // parse all flags flag.Parse() - c := loadConfig(*configPath) + c := loadconfig(*configPath) // check if flags are set if *configPath == "" { @@ -44,8 +44,8 @@ func main() { serveJSON() } -func loadConfig(file string) Config { - var config Config +func loadconfig(file string) config { + var config config configFile, err := os.Open(file) if err != nil { log.Fatalln(err) @@ -64,7 +64,7 @@ func itob(i int) bool { } //Unifi Controller API processing -func processUcAPIs(c Config) ([]node, []link) { +func processUcAPIs(c config) ([]node, []link) { //get list of Unifi devices to display var nodes []node var links []link @@ -148,7 +148,7 @@ func processUcAPIs(c Config) ([]node, []link) { } //UNMS API processing (Richtfunk) -func processUNMSAPI(c Config) ([]node, []link) { +func processUNMSAPI(c config) ([]node, []link) { // Variables for runtime var links []link var nodes []node @@ -238,18 +238,22 @@ func processUNMSAPI(c Config) ([]node, []link) { return nodes, links } -func processAPIs(c Config) { +func processAPIs(c config) { tick := time.Tick(delay) for range tick { var nodes []node var links []link - unmsNodes, unmsLinks := processUNMSAPI(c) - ucNodes, ucLinks := processUcAPIs(c) - nodes = append(nodes, unmsNodes...) - nodes = append(nodes, ucNodes...) - links = append(links, unmsLinks...) - links = append(links, ucLinks...) + if c.Unms.Enabled == true { + unmsNodes, unmsLinks := processUNMSAPI(c) + nodes = append(nodes, unmsNodes...) + links = append(links, unmsLinks...) + } + if c.Unifi.Enabled == true { + ucNodes, ucLinks := processUcAPIs(c) + nodes = append(nodes, ucNodes...) + links = append(links, ucLinks...) + } // assemble final struct o := output{ @@ -295,7 +299,7 @@ func getDevices(url string) (devices, error) { return d, nil } -func callUnifiAPI(c Config, url string, i interface{}) error { +func callUnifiAPI(c config, url string, i interface{}) error { request, err := http.NewRequest(http.MethodGet, c.Unms.UnmsAPIURL+url, nil) if err != nil { return errors.New(fmt.Sprint("can't set request", c.Unms.UnmsAPIURL+url)) diff --git a/types.go b/types.go index c152b25..1f69650 100644 --- a/types.go +++ b/types.go @@ -10,15 +10,15 @@ import ( "time" ) -type Config struct { +type config struct { Unms struct { - Active string `json:"active"` + Enabled bool `json:"enabled"` UnmsAPIURL string `json:"unmsAPIUrl"` APItoken string `json:"APItoken"` DevicesURL string `json:"devicesURL"` } `json:"unms"` Unifi struct { - Active string `json:"active"` + Enabled bool `json:"enabled"` APIURL string `json:"APIUrl"` User string `json:"user"` Password string `json:"password"` From e292e304c382fddd4162d2bd0ebdd8f0f5c0c1bd Mon Sep 17 00:00:00 2001 From: Nils Jakobi Date: Sun, 7 Feb 2021 21:29:30 +0100 Subject: [PATCH 5/6] made callUnifiAPI, processAPIs, processUNMSAPI functions for config type --- go.mod | 2 -- go.sum | 16 ---------------- main.go | 26 +++++++++++--------------- 3 files changed, 11 insertions(+), 33 deletions(-) diff --git a/go.mod b/go.mod index 185622d..13f5908 100644 --- a/go.mod +++ b/go.mod @@ -1,5 +1,3 @@ module git.freifunk-rhein-sieg.net/Freifunk-Troisdorf/ubnt-freifunk-map-api go 1.16 - -require git.nils.zone/nils/prettify v0.0.4 diff --git a/go.sum b/go.sum index 8ec57a6..e69de29 100644 --- a/go.sum +++ b/go.sum @@ -1,16 +0,0 @@ -git.nils.zone/nils/prettify v0.0.4 h1:y014Ejp0yhFAc9vu5U0nJRFxtXN6k6eWW6LiUkwn4NQ= -git.nils.zone/nils/prettify v0.0.4/go.mod h1:q4ydEhSvXuywHe5U6uSEoEeS9f2Upz/n8z0MJylLz5c= -github.com/TylerBrock/colorjson v0.0.0-20200706003622-8a50f05110d2 h1:ZBbLwSJqkHBuFDA6DUhhse0IGJ7T5bemHyNILUjvOq4= -github.com/TylerBrock/colorjson v0.0.0-20200706003622-8a50f05110d2/go.mod h1:VSw57q4QFiWDbRnjdX8Cb3Ow0SFncRw+bA/ofY6Q83w= -github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s= -github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= -github.com/hokaccha/go-prettyjson v0.0.0-20190818114111-108c894c2c0e h1:0aewS5NTyxftZHSnFaJmWE5oCCrj4DyEXkAiMa1iZJM= -github.com/hokaccha/go-prettyjson v0.0.0-20190818114111-108c894c2c0e/go.mod h1:pFlLw2CfqZiIBOx6BuCeRLCrfxBJipTY0nIOF/VbGcI= -github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA= -github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= -github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM= -github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4= -golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= diff --git a/main.go b/main.go index dc69628..0bd87bb 100644 --- a/main.go +++ b/main.go @@ -14,13 +14,9 @@ import ( "strconv" "strings" "time" - - _ "git.nils.zone/nils/prettify" ) -const ( - iso8601 = "2006-01-02T15:04:05-0700" -) +const iso8601 = "2006-01-02T15:04:05-0700" // flags var configPath = flag.String("configPath", "config.json", "Path to config.json") @@ -38,7 +34,7 @@ func main() { log.Fatalln("Please specify path to config.json flag '-configPath'") } // start API processing (runs in a loop) - go processAPIs(c) + go c.processAPIs() // start webserver on Port 3000 serveJSON() @@ -64,7 +60,7 @@ func itob(i int) bool { } //Unifi Controller API processing -func processUcAPIs(c config) ([]node, []link) { +func (c config) processUcAPIs() ([]node, []link) { //get list of Unifi devices to display var nodes []node var links []link @@ -148,7 +144,7 @@ func processUcAPIs(c config) ([]node, []link) { } //UNMS API processing (Richtfunk) -func processUNMSAPI(c config) ([]node, []link) { +func (c config) processUNMSAPI() ([]node, []link) { // Variables for runtime var links []link var nodes []node @@ -161,7 +157,7 @@ func processUNMSAPI(c config) ([]node, []link) { // API CALL 1 log.Println("calling API 1") var u []unifiAPIResponse - err = callUnifiAPI(c, "/devices", &u) + err = c.callUnifiAPI("/devices", &u) if err != nil { log.Fatalln(err) } @@ -185,13 +181,13 @@ func processUNMSAPI(c config) ([]node, []link) { // API CALL 2 log.Println("calling API 2 for device", d.Devices[i].Name) var details unifiAPIDetails - callUnifiAPI(c, "/devices/erouters/"+dev.Identification.ID, &details) + c.callUnifiAPI("/devices/erouters/"+dev.Identification.ID, &details) // END OF API CALL 2 // API CALL 3 log.Println("calling API 3 for device", d.Devices[i].Name) var airmaxes []unifiAPIAirmax - callUnifiAPI(c, "/devices/airmaxes/"+dev.Identification.ID+"/stations", &airmaxes) + c.callUnifiAPI("/devices/airmaxes/"+dev.Identification.ID+"/stations", &airmaxes) // check if remote mac address is part of our published network for i := range airmaxes { if isRemoteMACpublished(airmaxes[i].DeviceIdentification.MAC, d.Devices) == true { @@ -238,19 +234,19 @@ func processUNMSAPI(c config) ([]node, []link) { return nodes, links } -func processAPIs(c config) { +func (c config) processAPIs() { tick := time.Tick(delay) for range tick { var nodes []node var links []link if c.Unms.Enabled == true { - unmsNodes, unmsLinks := processUNMSAPI(c) + unmsNodes, unmsLinks := c.processUNMSAPI() nodes = append(nodes, unmsNodes...) links = append(links, unmsLinks...) } if c.Unifi.Enabled == true { - ucNodes, ucLinks := processUcAPIs(c) + ucNodes, ucLinks := c.processUcAPIs() nodes = append(nodes, ucNodes...) links = append(links, ucLinks...) } @@ -299,7 +295,7 @@ func getDevices(url string) (devices, error) { return d, nil } -func callUnifiAPI(c config, url string, i interface{}) error { +func (c config) callUnifiAPI(url string, i interface{}) error { request, err := http.NewRequest(http.MethodGet, c.Unms.UnmsAPIURL+url, nil) if err != nil { return errors.New(fmt.Sprint("can't set request", c.Unms.UnmsAPIURL+url)) From 831ce76e79c77516ca49ee1534ede9579e8f44f9 Mon Sep 17 00:00:00 2001 From: Stefan Hoffmann Date: Wed, 10 Feb 2021 19:31:31 +0100 Subject: [PATCH 6/6] use global variable for config --- go.mod | 2 ++ go.sum | 16 ++++++++++++++++ main.go | 46 +++++++++++++++++++++++++--------------------- 3 files changed, 43 insertions(+), 21 deletions(-) diff --git a/go.mod b/go.mod index 13f5908..185622d 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module git.freifunk-rhein-sieg.net/Freifunk-Troisdorf/ubnt-freifunk-map-api go 1.16 + +require git.nils.zone/nils/prettify v0.0.4 diff --git a/go.sum b/go.sum index e69de29..8ec57a6 100644 --- a/go.sum +++ b/go.sum @@ -0,0 +1,16 @@ +git.nils.zone/nils/prettify v0.0.4 h1:y014Ejp0yhFAc9vu5U0nJRFxtXN6k6eWW6LiUkwn4NQ= +git.nils.zone/nils/prettify v0.0.4/go.mod h1:q4ydEhSvXuywHe5U6uSEoEeS9f2Upz/n8z0MJylLz5c= +github.com/TylerBrock/colorjson v0.0.0-20200706003622-8a50f05110d2 h1:ZBbLwSJqkHBuFDA6DUhhse0IGJ7T5bemHyNILUjvOq4= +github.com/TylerBrock/colorjson v0.0.0-20200706003622-8a50f05110d2/go.mod h1:VSw57q4QFiWDbRnjdX8Cb3Ow0SFncRw+bA/ofY6Q83w= +github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s= +github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= +github.com/hokaccha/go-prettyjson v0.0.0-20190818114111-108c894c2c0e h1:0aewS5NTyxftZHSnFaJmWE5oCCrj4DyEXkAiMa1iZJM= +github.com/hokaccha/go-prettyjson v0.0.0-20190818114111-108c894c2c0e/go.mod h1:pFlLw2CfqZiIBOx6BuCeRLCrfxBJipTY0nIOF/VbGcI= +github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA= +github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM= +github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= diff --git a/main.go b/main.go index 0bd87bb..e9dcd30 100644 --- a/main.go +++ b/main.go @@ -14,27 +14,31 @@ import ( "strconv" "strings" "time" + + _ "git.nils.zone/nils/prettify" ) -const iso8601 = "2006-01-02T15:04:05-0700" +const ( + iso8601 = "2006-01-02T15:04:05-0700" +) // flags var configPath = flag.String("configPath", "config.json", "Path to config.json") var version = "development" var delay time.Duration = 60 * time.Second +var conf = loadconfig(*configPath) func main() { log.Printf("starting version %s...\n", version) // parse all flags flag.Parse() - c := loadconfig(*configPath) // check if flags are set if *configPath == "" { log.Fatalln("Please specify path to config.json flag '-configPath'") } // start API processing (runs in a loop) - go c.processAPIs() + go processAPIs() // start webserver on Port 3000 serveJSON() @@ -60,16 +64,16 @@ func itob(i int) bool { } //Unifi Controller API processing -func (c config) processUcAPIs() ([]node, []link) { +func processUcAPIs() ([]node, []link) { //get list of Unifi devices to display var nodes []node var links []link - d, err := getDevices(c.Unifi.UCDevicesURL) + d, err := getDevices(conf.Unifi.UCDevicesURL) if err != nil { log.Fatalln(err) } //call Unifi Controller - ucAPI := newAPI(c.Unifi.User, c.Unifi.Password, c.Unifi.APIURL) + ucAPI := newAPI(conf.Unifi.User, conf.Unifi.Password, conf.Unifi.APIURL) //login ucAPI.ucLogin() //get all Sites from Controller @@ -144,12 +148,12 @@ func (c config) processUcAPIs() ([]node, []link) { } //UNMS API processing (Richtfunk) -func (c config) processUNMSAPI() ([]node, []link) { +func processUNMSAPI() ([]node, []link) { // Variables for runtime var links []link var nodes []node - d, err := getDevices(c.Unms.DevicesURL) + d, err := getDevices(conf.Unms.DevicesURL) if err != nil { log.Fatalln(err) } @@ -157,7 +161,7 @@ func (c config) processUNMSAPI() ([]node, []link) { // API CALL 1 log.Println("calling API 1") var u []unifiAPIResponse - err = c.callUnifiAPI("/devices", &u) + err = callUnifiAPI("/devices", &u) if err != nil { log.Fatalln(err) } @@ -181,13 +185,13 @@ func (c config) processUNMSAPI() ([]node, []link) { // API CALL 2 log.Println("calling API 2 for device", d.Devices[i].Name) var details unifiAPIDetails - c.callUnifiAPI("/devices/erouters/"+dev.Identification.ID, &details) + callUnifiAPI("/devices/erouters/"+dev.Identification.ID, &details) // END OF API CALL 2 // API CALL 3 log.Println("calling API 3 for device", d.Devices[i].Name) var airmaxes []unifiAPIAirmax - c.callUnifiAPI("/devices/airmaxes/"+dev.Identification.ID+"/stations", &airmaxes) + callUnifiAPI("/devices/airmaxes/"+dev.Identification.ID+"/stations", &airmaxes) // check if remote mac address is part of our published network for i := range airmaxes { if isRemoteMACpublished(airmaxes[i].DeviceIdentification.MAC, d.Devices) == true { @@ -234,19 +238,19 @@ func (c config) processUNMSAPI() ([]node, []link) { return nodes, links } -func (c config) processAPIs() { +func processAPIs() { tick := time.Tick(delay) for range tick { var nodes []node var links []link - if c.Unms.Enabled == true { - unmsNodes, unmsLinks := c.processUNMSAPI() + if conf.Unms.Enabled == true { + unmsNodes, unmsLinks := processUNMSAPI() nodes = append(nodes, unmsNodes...) links = append(links, unmsLinks...) } - if c.Unifi.Enabled == true { - ucNodes, ucLinks := c.processUcAPIs() + if conf.Unifi.Enabled == true { + ucNodes, ucLinks := processUcAPIs() nodes = append(nodes, ucNodes...) links = append(links, ucLinks...) } @@ -295,16 +299,16 @@ func getDevices(url string) (devices, error) { return d, nil } -func (c config) callUnifiAPI(url string, i interface{}) error { - request, err := http.NewRequest(http.MethodGet, c.Unms.UnmsAPIURL+url, nil) +func callUnifiAPI(url string, i interface{}) error { + request, err := http.NewRequest(http.MethodGet, conf.Unms.UnmsAPIURL+url, nil) if err != nil { - return errors.New(fmt.Sprint("can't set request", c.Unms.UnmsAPIURL+url)) + return errors.New(fmt.Sprint("can't set request", conf.Unms.UnmsAPIURL+url)) } - request.Header.Set("x-auth-token", c.Unms.APItoken) + request.Header.Set("x-auth-token", conf.Unms.APItoken) client := &http.Client{} response, err := client.Do(request) if err != nil { - return fmt.Errorf("can't get request %s with x-auth-token %s", c.Unms.UnmsAPIURL+url, c.Unms.APItoken) + return fmt.Errorf("can't get request %s with x-auth-token %s", conf.Unms.UnmsAPIURL+url, conf.Unms.APItoken) } if response.StatusCode != 200 { log.Fatalln("Can´t call UNMS API, check token and URL. HTTP Status: ", response.StatusCode)