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) <[email protected]>
  • Loading branch information
welteki committed Dec 15, 2023
1 parent 9b0d8fb commit bc2b156
Showing 1 changed file with 35 additions and 1 deletion.
36 changes: 35 additions & 1 deletion printer/handler.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,54 @@
package function

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

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

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

return out.Bytes(), err
}

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 bc2b156

Please sign in to comment.