Initial commit

This commit is contained in:
Alexis Vanier
2020-01-09 17:06:03 -05:00
committed by Alexis Vanier
commit ebbf79ce68
23 changed files with 1443 additions and 0 deletions

94
util/util.go Normal file
View File

@@ -0,0 +1,94 @@
package util
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"github.com/spf13/pflag"
)
func HandleError(err error) {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
// ParseSource returns the struct of parsed source options.
func ParseSource(cmdFlags *pflag.FlagSet) STDINPayload {
var (
inputFile string
sourceData []byte
stdinPayload STDINPayload
err error
)
// Set default values of our source object
stdinPayload.Source.Insecure = false
stdinPayload.Source.SkipSSLVerification = false
stdinPayload.Source.Port = "443"
stdinPayload.Version.Number = "0"
inputFile, err = cmdFlags.GetString("file")
if err != nil {
HandleError(err)
}
// If a config
if inputFile == "" {
sourceData, err = parseStdin()
} else {
sourceData, err = ioutil.ReadFile(inputFile)
}
if err != nil {
HandleError(err)
}
err = json.Unmarshal(sourceData, &stdinPayload)
if err != nil {
HandleError(err)
}
return stdinPayload
}
func parseStdin() ([]byte, error) {
stat, _ := os.Stdin.Stat()
var (
bytes []byte
err error
)
if (stat.Mode() & os.ModeCharDevice) == 0 {
bytes, err = ioutil.ReadAll(os.Stdin)
} else {
bytes, err = nil, errors.New("no data found in stdin")
}
return bytes, err
}
// CheckResponse deals with http responses and automatically crashes the app
// if needed
func CheckResponse(response *http.Response) {
if response.StatusCode != http.StatusOK {
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
HandleError(err)
}
bodyString := string(bodyBytes)
fmt.Fprintf(os.Stderr, "request url: %s\n", response.Request.URL)
fmt.Fprintf(os.Stderr, "code: %d\n", response.StatusCode)
fmt.Fprintln(os.Stderr, bodyString)
os.Exit(1)
}
}