Files
gitea-resource/util/util.go
Alexis Vanier ebbf79ce68 Initial commit
2020-01-11 01:43:50 -05:00

95 lines
1.7 KiB
Go

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)
}
}