added webserver to serve json file. also running indefinitely now

This commit is contained in:
Nils Stinnesbeck 2021-01-02 22:16:07 +01:00
parent 94222942e6
commit 78b274c160

46
main.go
View File

@ -23,18 +23,27 @@ const (
// flags
var token = flag.String("token", "", "Defines the x-auth-token")
var version = "development"
var delay time.Duration = 60 * time.Second
func main() {
log.Println("starting version", version, "...")
log.Printf("starting version %s...\n", version)
// parse all flags
flag.Parse()
// check if token is set
if *token == "" {
log.Fatalln("Please specify an API token via the flag '-token'")
}
// start API processing (runs in a loop)
go processAPIs()
// start webserver
serveJSON()
}
func processAPIs() {
tick := time.Tick(delay)
for range tick {
// Variables for runtime
var links []link
var nodes []node
@ -131,11 +140,15 @@ func main() {
// create file output
log.Println("writing json file")
writeJSONtoFile(o)
if err := o.writeToFile(); err != nil {
log.Fatalln(err)
}
// we're done here
log.Println("...done")
}
}
func getDevices() (devices, error) {
// get devices from JSON file
@ -213,22 +226,19 @@ func addLink(dev unifiAPIResponse, airmaxes unifiAPIAirmax, links []link) []link
return links
}
func writeJSONtoFile(o output) error {
file, err := json.MarshalIndent(o, "", " ")
if err != nil {
return fmt.Errorf("can't marshal to json: %+v", o)
}
// write to file
err = ioutil.WriteFile("example.json", file, 0644)
if err != nil {
return fmt.Errorf("can't write to json file example.json")
}
return nil
}
func getAddresses(ip string) []string {
var adresses []string
adresses = append(adresses, strings.Split(ip, "/")[0])
return adresses
}
func serveJSON() {
fs := http.FileServer(http.Dir("./output"))
http.Handle("/", fs)
log.Println("Listening on :3000...")
err := http.ListenAndServe(":3000", nil)
if err != nil {
log.Fatalln(err)
}
}