Skip to content

Commit

Permalink
Support pretty json printing
Browse files Browse the repository at this point in the history
Signed-off-by: Han Verstraete (OpenFaaS Ltd) <han@openfaas.com>
  • Loading branch information
welteki authored and alexellis committed Dec 15, 2023
1 parent 9b0d8fb commit 0cd9790
Showing 1 changed file with 34 additions and 1 deletion.
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

0 comments on commit 0cd9790

Please sign in to comment.