Skip to content

Commit

Permalink
Add format flag to listen cmd (stripe#615)
Browse files Browse the repository at this point in the history
  • Loading branch information
gracegoo-stripe authored Mar 18, 2021
1 parent 64c9619 commit fb121ab
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 4 deletions.
8 changes: 7 additions & 1 deletion pkg/cmd/listen.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ type listenCmd struct {
livemode bool
useConfiguredWebhooks bool
printJSON bool
format string
skipVerify bool
onlyPrintSecret bool
skipUpdate bool
Expand Down Expand Up @@ -64,7 +65,11 @@ Stripe account.`,
lc.cmd.Flags().StringVarP(&lc.forwardConnectURL, "forward-connect-to", "c", "", "The URL to forward Connect webhook events to (default: same as normal events)")
lc.cmd.Flags().BoolVarP(&lc.latestAPIVersion, "latest", "l", false, "Receive events formatted with the latest API version (default: your account's default API version)")
lc.cmd.Flags().BoolVar(&lc.livemode, "live", false, "Receive live events (default: test)")
lc.cmd.Flags().BoolVarP(&lc.printJSON, "print-json", "j", false, "Print full JSON objects to stdout")
lc.cmd.Flags().BoolVarP(&lc.printJSON, "print-json", "j", false, "Print full JSON objects to stdout.")
lc.cmd.Flags().MarkDeprecated("print-json", "Please use `--format JSON` instead and use `jq` if you need to process the JSON in the terminal.")
lc.cmd.Flags().StringVar(&lc.format, "format", "", `Specifies the output format of webhook events
Acceptable values:
'JSON' - Output webhook events in JSON format`)
lc.cmd.Flags().BoolVarP(&lc.useConfiguredWebhooks, "use-configured-webhooks", "a", false, "Load webhook endpoint configuration from the webhooks API/dashboard")
lc.cmd.Flags().BoolVarP(&lc.skipVerify, "skip-verify", "", false, "Skip certificate verification when forwarding to HTTPS endpoints")
lc.cmd.Flags().BoolVar(&lc.onlyPrintSecret, "print-secret", false, "Only print the webhook signing secret and exit")
Expand Down Expand Up @@ -170,6 +175,7 @@ func (lc *listenCmd) runListenCmd(cmd *cobra.Command, args []string) error {
APIBaseURL: lc.apiBaseURL,
WebSocketFeature: webhooksWebSocketFeature,
PrintJSON: lc.printJSON,
Format: lc.format,
UseLatestAPIVersion: lc.latestAPIVersion,
SkipVerify: lc.skipVerify,
Log: log.StandardLogger(),
Expand Down
3 changes: 2 additions & 1 deletion pkg/logtailing/tailer.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"os"
"os/signal"
"reflect"
"strings"
"syscall"
"time"

Expand Down Expand Up @@ -257,7 +258,7 @@ func (t *Tailer) processRequestLogEvent(msg websocket.IncomingMessage) {
return
}

if t.cfg.OutputFormat == outputFormatJSON {
if strings.ToUpper(t.cfg.OutputFormat) == outputFormatJSON {
fmt.Println(ansi.ColorizeJSON(requestLogEvent.EventPayload, false, os.Stdout))
return
}
Expand Down
32 changes: 30 additions & 2 deletions pkg/proxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"

Expand Down Expand Up @@ -59,6 +60,9 @@ type Config struct {
// Indicates whether to print full JSON objects to stdout
PrintJSON bool

// Specifies the format to print to stdout.
Format string

// Indicates whether to filter events formatted with the default or latest API version
UseLatestAPIVersion bool

Expand Down Expand Up @@ -230,6 +234,25 @@ func (p *Proxy) filterWebhookEvent(msg *websocket.WebhookEvent) bool {
return false
}

// This function outputs the event payload in the format specified.
// Currently only supports JSON.
func (p *Proxy) formatOutput(format string, eventPayload string) {
var event map[string]interface{}
err := json.Unmarshal([]byte(eventPayload), &event)
if err != nil {
p.cfg.Log.Debug("Received malformed event from Stripe, ignoring")
return
}
switch strings.ToUpper(format) {
// The distinction between this and PrintJSON is that this output is stripped of all pretty format.
case outputFormatJSON:
outputJSON, _ := json.Marshal(event)
fmt.Println(ansi.ColorizeJSON(string(outputJSON), false, os.Stdout))
default:
fmt.Printf("Unrecognized output format %s\n" + format)
}
}

func (p *Proxy) processWebhookEvent(msg websocket.IncomingMessage) {
if msg.WebhookEvent == nil {
p.cfg.Log.Debug("WebSocket specified for Webhooks received non-webhook event")
Expand Down Expand Up @@ -263,9 +286,12 @@ func (p *Proxy) processWebhookEvent(msg websocket.IncomingMessage) {
}

if p.events["*"] || p.events[evt.Type] {
if p.cfg.PrintJSON {
switch {
case p.cfg.PrintJSON:
fmt.Println(webhookEvent.EventPayload)
} else {
case len(p.cfg.Format) > 0:
p.formatOutput(p.cfg.Format, webhookEvent.EventPayload)
default:
maybeConnect := ""
if evt.isConnect() {
maybeConnect = "connect "
Expand Down Expand Up @@ -417,6 +443,8 @@ const (
maxHeaderValueSize = 200
)

const outputFormatJSON = "JSON"

//
// Private functions
//
Expand Down

0 comments on commit fb121ab

Please sign in to comment.