mirror of
https://github.com/fnproject/fn.git
synced 2022-10-28 21:29:17 +03:00
Returning error instead of writing it to a response writer
This commit is contained in:
@@ -3,7 +3,6 @@ package protocol
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
@@ -82,14 +81,12 @@ func (h *JSONProtocol) DumpJSON(w io.Writer, req *http.Request) error {
|
|||||||
func (h *JSONProtocol) Dispatch(w io.Writer, req *http.Request) error {
|
func (h *JSONProtocol) Dispatch(w io.Writer, req *http.Request) error {
|
||||||
err := h.DumpJSON(w, req)
|
err := h.DumpJSON(w, req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return respondWithError(
|
return err
|
||||||
w, fmt.Errorf("unable to write JSON into STDIN: %s", err.Error()))
|
|
||||||
}
|
}
|
||||||
jout := new(JSONIO)
|
jout := new(JSONIO)
|
||||||
dec := json.NewDecoder(h.out)
|
dec := json.NewDecoder(h.out)
|
||||||
if err := dec.Decode(jout); err != nil {
|
if err := dec.Decode(jout); err != nil {
|
||||||
return respondWithError(
|
return err
|
||||||
w, fmt.Errorf("unable to decode JSON response object: %s", err.Error()))
|
|
||||||
}
|
}
|
||||||
if rw, ok := w.(http.ResponseWriter); ok {
|
if rw, ok := w.(http.ResponseWriter); ok {
|
||||||
// this has to be done for pulling out:
|
// this has to be done for pulling out:
|
||||||
@@ -104,30 +101,14 @@ func (h *JSONProtocol) Dispatch(w io.Writer, req *http.Request) error {
|
|||||||
rw.WriteHeader(jout.StatusCode)
|
rw.WriteHeader(jout.StatusCode)
|
||||||
_, err = rw.Write([]byte(jout.Body)) // TODO timeout
|
_, err = rw.Write([]byte(jout.Body)) // TODO timeout
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return respondWithError(
|
return err
|
||||||
w, fmt.Errorf("unable to write JSON response object: %s", err.Error()))
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// logs can just copy the full thing in there, headers and all.
|
// logs can just copy the full thing in there, headers and all.
|
||||||
err = json.NewEncoder(w).Encode(jout)
|
err = json.NewEncoder(w).Encode(jout)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return respondWithError(
|
return err
|
||||||
w, fmt.Errorf("error writing function response: %s", err.Error()))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func respondWithError(w io.Writer, err error) error {
|
|
||||||
errMsg := []byte(err.Error())
|
|
||||||
statusCode := http.StatusInternalServerError
|
|
||||||
if rw, ok := w.(http.ResponseWriter); ok {
|
|
||||||
rw.WriteHeader(statusCode)
|
|
||||||
rw.Write(errMsg)
|
|
||||||
} else {
|
|
||||||
// logs can just copy the full thing in there, headers and all.
|
|
||||||
w.Write(errMsg)
|
|
||||||
}
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user