Skip to content

Commit

Permalink
Merge pull request #206 from traviscampbell/finish-gron-mon
Browse files Browse the repository at this point in the history
finished last bit of the gron outputter implementation
  • Loading branch information
danielgtaylor authored Aug 1, 2023
2 parents 3a541b4 + a5dcceb commit 1d22b51
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
9 changes: 7 additions & 2 deletions cli/content.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,13 @@ func setTable(data []interface{}) ([]byte, error) {
// available as a built-in Restish output option.
type Gron struct{}

// Detect if the content type is gron.
// Detect if the content type is gron-able.
func (t Gron) Detect(contentType string) bool {
first := strings.Split(contentType, ";")[0]
if first == "application/json" || strings.HasSuffix(first, "+json") {
return true
}

return false
}

Expand All @@ -265,7 +270,7 @@ func (t Gron) Marshal(value interface{}) ([]byte, error) {

// Unmarshal the value from a gron string.
func (t Gron) Unmarshal(data []byte, value interface{}) error {
return fmt.Errorf("unimplemented")
return json.Unmarshal(data, value)
}

// JSON describes content types like `application/json` or
Expand Down
14 changes: 11 additions & 3 deletions cli/gron.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cli

import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
Expand Down Expand Up @@ -175,11 +176,18 @@ func marshalGron(pb *PathBuffer, data any, isAnon bool, out []byte) ([]byte, err
}
default:
// This is a primitive type, just take the JSON representation.
v, err := json.Marshal(data)
if err != nil {
// The default encoder escapes '<', '>', and '&' which we don't want
// since we are not a browser. Disable this with an encoder instance.
// See https://stackoverflow.com/a/28596225/164268
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
if err := enc.Encode(makeJSONSafe(data)); err != nil {
return nil, err
}
out = apnd(out, pb.Bytes(), " = ", v, ";\n")
// Note: encoder adds it's own ending newline we need to strip out.
b := bytes.TrimSuffix(buf.Bytes(), []byte("\n"))
out = apnd(out, pb.Bytes(), " = ", b, ";\n")
}

return out, nil
Expand Down
4 changes: 2 additions & 2 deletions cli/gron_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func TestGronMarshal(t *testing.T) {
B: 42,
C: true,
D: D{[]map[string]any{
{"e": "world"},
{"e": "world & i <3 restish"},
{"f": []any{1, 2}, "g": time.Time{}, "h": []byte("foo")},
{"for": map[int]int{1: 2}},
}},
Expand All @@ -42,7 +42,7 @@ body.b = 42;
body.c = true;
body.d = [];
body.d[0] = {};
body.d[0].e = "world";
body.d[0].e = "world & i <3 restish";
body.d[1] = {};
body.d[1].f = [];
body.d[1].f[0] = 1;
Expand Down

0 comments on commit 1d22b51

Please sign in to comment.