Skip to content

Commit

Permalink
Merge pull request #6 from tiket-oss/features
Browse files Browse the repository at this point in the history
adding http output feature
  • Loading branch information
asdptkt authored Apr 12, 2019
2 parents d3d051b + 48ebc04 commit 3c63973
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions cmd/decoder/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,18 @@ import (
"github.com/tiket-oss/go-pxld"
"gopkg.in/alecthomas/kingpin.v2"

"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"time"
)

var (
targetFile = kingpin.Flag("target", "Target file to decode").Required().ExistingFile()
output = kingpin.Flag("output", "Output of this, can be file path or omit if stdout").Default("").String()
output = kingpin.Flag("output", "Output of this, can be file path, http address (60s timeout), or omit to stdout").Default("").String()
repeatEvery = kingpin.Flag("repeat", "Repeat reading from the target file every n seconds, useful for reading logrotated file").Duration()
)

Expand Down Expand Up @@ -53,9 +56,28 @@ func do() {
log.Fatalf("Unexpected error while marshaling file %s to JSON: %v", *targetFile, err)
}

err = ioutil.WriteFile(*output, raw, 0644)
if err != nil {
log.Fatalf("Unexpected error while writing file %s JSON to %s: %v", *targetFile, *output, err)
if isValidURL(*output) {
cli := &http.Client{
Timeout: time.Minute,
}
res, err := cli.Post(*output, "application/json", bytes.NewReader(raw))
if err != nil {
log.Fatalf("Unexpected error while sending file %s JSON to %s: %v", *targetFile, *output, err)
}
if res.StatusCode >= http.StatusBadRequest {
err = fmt.Errorf("invalid response status code %d", res.StatusCode)
log.Fatalf("Unexpected error while sending file %s JSON to %s: %v", *targetFile, *output, err)
}
} else {
err = ioutil.WriteFile(*output, raw, 0644)
if err != nil {
log.Fatalf("Unexpected error while writing file %s JSON to %s: %v", *targetFile, *output, err)
}
}
}
}

func isValidURL(toTest string) bool {
_, err := url.ParseRequestURI(toTest)
return err == nil
}

0 comments on commit 3c63973

Please sign in to comment.