]> de.git.xonotic.org Git - xonotic/xonstat.git/commitdiff
Clean up xs_submit.
authorAnt Zucaro <azucaro@gmail.com>
Sun, 29 Nov 2015 15:07:55 +0000 (10:07 -0500)
committerAnt Zucaro <azucaro@gmail.com>
Sun, 29 Nov 2015 15:07:55 +0000 (10:07 -0500)
This was written when I didn't really know that much Golang. I know a little
bit more about it now, so I can at least format accordingly! Also I know how to
use a Scanner now. Shame on my past self...

xonstat/util/xs_submit.go

index 652eb85077acfc127c6977f03db614890cb03e7c..1b962549adc2c16c20151ec96e6b7cb1b7dbdd5c 100644 (file)
@@ -1,32 +1,54 @@
 package main
 
-import "bytes"
-import "flag"
-import "fmt"
-import "io/ioutil"
-import "net/http"
-import "os"
+import (
+       "bufio"
+       "bytes"
+       "flag"
+       "fmt"
+       "io/ioutil"
+       "net/http"
+       "os"
+)
 
 /* xs_submit takes a file containing a single XonStat request and submits it
    to the server URL specified */
 func main() {
-  var fn = flag.String("file", "xonstat.log", "Logfile from XonStat")
-  var url = flag.String("url", "http://localhost:6543/stats/submit", "XonStat submission URL")
-  flag.Parse()
+       fn := flag.String("file", "xonstat.log", "Logfile from XonStat")
+       url := flag.String("url", "http://localhost:6543/stats/submit", "XonStat submission URL")
+       out := flag.Bool("out", false, "logs the response body to <file>.out")
+       flag.Parse()
 
-  body, err := ioutil.ReadFile(*fn)
-  if err != nil {
-    fmt.Printf("Issue opening file %s\n", *fn)
-    os.Exit(1)
-  }
-  contentlength := int64(len(body))
+       body, err := ioutil.ReadFile(*fn)
+       if err != nil {
+               fmt.Printf("Issue opening file %s\n", *fn)
+               os.Exit(1)
+       }
+       contentlength := int64(len(body))
 
-  r := bytes.NewReader(body)
+       r := bytes.NewReader(body)
 
-  req, _ := http.NewRequest("POST", *url, r)
-  req.ContentLength = contentlength
-  res, _ := http.DefaultClient.Do(req)
-  defer res.Body.Close()
+       req, _ := http.NewRequest("POST", *url, r)
+       req.ContentLength = contentlength
+       res, _ := http.DefaultClient.Do(req)
+       defer res.Body.Close()
 
-  fmt.Printf("%s: %s\n", *fn, res.Status)
+       fmt.Printf("%s: %s\n", *fn, res.Status)
+
+       if *out {
+               // open the output file for the response
+               of, err := os.Create(*fn + ".out")
+               if err != nil {
+                       fmt.Printf("Issue creating file %s.out\n", *fn)
+                       os.Exit(1)
+               }
+               defer of.Close()
+
+               bo := bufio.NewWriter(of)
+               defer bo.Flush()
+
+               scanner := bufio.NewScanner(res.Body)
+               for scanner.Scan() {
+                       fmt.Fprintln(bo, scanner.Text())
+               }
+       }
 }