Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(outputTemplate): unescape string output #371

Merged
merged 1 commit into from
May 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 22 additions & 6 deletions pkg/request/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -799,7 +799,7 @@ func (r *RequestHandler) ProcessResponse(resp *c8y.Response, respError error, in
}
}

if resp != nil && respError == nil && (r.Config.IsResponseOutput() || resp.Response.Header.Get("Content-Type") == "application/octet-stream") && len(resp.Body()) > 0 {
if resp != nil && respError == nil && !hasOutputTemplate && (r.Config.IsResponseOutput() || resp.Response.Header.Get("Content-Type") == "application/octet-stream") && len(resp.Body()) > 0 {
// estimate size based on utf8 encoding. 1 char is 1 byte
r.Logger.Debugf("Writing https response output")

Expand Down Expand Up @@ -873,11 +873,27 @@ func (r *RequestHandler) ProcessResponse(resp *c8y.Response, respError error, in
resp.SetBody(pretty.Ugly(tmplOutput))
} else {
isJSONResponse = false
// TODO: Is removing the quotes doing too much, what happens if someone is building csv, and it using quotes around some fields?
// e.g. `"my value",100`, that would get transformed to `my value",100`
// Trim any quotes wrapping the values
tmplOutput = bytes.TrimSpace(tmplOutput)
resp.SetBody(bytes.Trim(tmplOutput, "\""))
// Try to unmarshal json for situations when the user has used "response.body"
// and body contains escaped json chars (e.g. \n)
// https://github.com/reubenmiller/go-c8y-cli/issues/306
var maybeJSON any
jsonErr := json.Unmarshal(tmplOutput, &maybeJSON)
skipTrimming := false
if jsonErr == nil {
switch v := maybeJSON.(type) {
case string:
tmplOutput = []byte(v)
skipTrimming = true
}
}
if !skipTrimming {
// TODO: Is removing the quotes doing too much, what happens if someone is building csv, and it using quotes around some fields?
// e.g. `"my value",100`, that would get transformed to `my value",100`
// Trim any quotes wrapping the values
tmplOutput = bytes.TrimSpace(tmplOutput)
tmplOutput = bytes.Trim(tmplOutput, "\"")
}
resp.SetBody(tmplOutput)
}
}

Expand Down
Loading