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

Pretty print json payloads in the printer function. #8

Merged
merged 1 commit into from
Dec 15, 2023
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
35 changes: 34 additions & 1 deletion printer/handler.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,53 @@
package function

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
)

func formatJSON(data []byte) ([]byte, error) {
var out bytes.Buffer

if err := json.Indent(&out, data, "", " "); err != nil {
return data, err
}

return out.Bytes(), nil
}

func printRaw() bool {
val := os.Getenv("RAW")
raw, err := strconv.ParseBool(val)
if err != nil {
return false
}
return raw
}

func Handle(w http.ResponseWriter, r *http.Request) {
var input []byte

contentType := r.Header.Get("content-type")
if r.Body != nil {
defer r.Body.Close()

body, _ := io.ReadAll(r.Body)

input = body
if !printRaw() && contentType == "application/json" {
var err error
input, err = formatJSON(body)
if err != nil {
http.Error(w, fmt.Sprintf("failed to format JSON body: %s", err), http.StatusInternalServerError)
return
}
} else {
input = body
}
}

for k, v := range r.Header {
Expand Down
Loading