From 5efe73b3cac4c6a815140129a31b7dc7aeb05f39 Mon Sep 17 00:00:00 2001 From: Buddy Sandidge Date: Thu, 19 Sep 2019 18:39:04 -0700 Subject: [PATCH] =?UTF-8?q?initial=20commit=20=E2=80=94=20makes=20requests?= =?UTF-8?q?=20and=20writes=20result=20to=20stdout?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.go | 103 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 main.go diff --git a/main.go b/main.go new file mode 100644 index 0000000..b895194 --- /dev/null +++ b/main.go @@ -0,0 +1,103 @@ +package main + +import ( + "encoding/json" + "flag" + "fmt" + "log" + "net/http" + "net/url" + "os" + "time" +) + +func main() { + if err := run(); err != nil { + log.Fatal(err) + } +} + +const ( + hostDefault = "127.0.0.1:8085" + hostDesc = "open hardware monitor host [OSHW_HOST]" +) + +func run() error { + conifg := getConfig() + node, err := fetchNode(conifg.host) + if err != nil { + return err + } + fmt.Printf("%s", node) + return nil +} + +type config struct { + host string +} + +func getConfig() *config { + c := config{} + host := os.Getenv("OHWM_HOST") + hostFlag := flag.String("host", hostDefault, hostDesc) + flag.Parse() + if *hostFlag != hostDefault { + host = *hostFlag + } + if host == "" { + host = hostDefault + } + c.host = host + return &c +} + +func fetchNode(host string) (*node, error) { + client := http.Client{Timeout: time.Second} + u := url.URL{Scheme: "http", Host: host, Path: "/data.json"} + resp, err := client.Get(u.String()) + if err != nil { + return nil, err + } + defer resp.Body.Close() + node := &node{} + decoder := json.NewDecoder(resp.Body) + if err := decoder.Decode(node); err != nil { + return nil, err + } + return node, nil +} + +type node struct { + ID int `json:"id"` + ImageURL string + Max string + Min string + Text string + Value string + Children []node +} + +func (n *node) String() string { + return n.stringify(0) +} + +func (n *node) stringify(indent int) string { + prefix := "" + for i := 0; i < indent; i++ { + prefix += " " + } + + ret := prefix + n.Text + if n.Value != "" { + ret += ": " + n.Value + } + if n.Max != "" && n.Min != "" && n.Max != "-" && n.Min != "-" { + ret += fmt.Sprintf(" (%s - %s)", n.Min, n.Max) + } + ret += "\n" + for _, child := range n.Children { + ret += child.stringify(indent + 1) + } + + return ret +}