2023-07-31 17:32:39 +00:00
|
|
|
package http
|
2023-03-28 16:44:41 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"strconv"
|
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
2023-07-20 16:26:40 +00:00
|
|
|
const (
|
|
|
|
jsonMediaType = "application/json"
|
|
|
|
octetStreamMediaType = "application/octet-stream"
|
|
|
|
)
|
|
|
|
|
2023-08-18 14:29:40 +00:00
|
|
|
type HasStatusCode interface {
|
|
|
|
StatusCode() int
|
|
|
|
}
|
|
|
|
|
2023-03-28 16:44:41 +00:00
|
|
|
// DefaultErrorJson is a JSON representation of a simple error value, containing only a message and an error code.
|
|
|
|
type DefaultErrorJson struct {
|
|
|
|
Message string `json:"message"`
|
|
|
|
Code int `json:"code"`
|
|
|
|
}
|
|
|
|
|
2023-08-18 14:29:40 +00:00
|
|
|
func (e *DefaultErrorJson) StatusCode() int {
|
|
|
|
return e.Code
|
|
|
|
}
|
|
|
|
|
2023-03-28 16:44:41 +00:00
|
|
|
// WriteJson writes the response message in JSON format.
|
|
|
|
func WriteJson(w http.ResponseWriter, v any) {
|
2023-07-20 16:26:40 +00:00
|
|
|
w.Header().Set("Content-Type", jsonMediaType)
|
2023-03-28 16:44:41 +00:00
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
if err := json.NewEncoder(w).Encode(v); err != nil {
|
|
|
|
log.WithError(err).Error("Could not write response message")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-20 16:26:40 +00:00
|
|
|
// WriteSsz writes the response message in ssz format
|
|
|
|
func WriteSsz(w http.ResponseWriter, respSsz []byte, fileName string) {
|
|
|
|
w.Header().Set("Content-Length", strconv.Itoa(len(respSsz)))
|
|
|
|
w.Header().Set("Content-Type", octetStreamMediaType)
|
|
|
|
w.Header().Set("Content-Disposition", "attachment; filename="+fileName)
|
|
|
|
if _, err := io.Copy(w, io.NopCloser(bytes.NewReader(respSsz))); err != nil {
|
|
|
|
log.WithError(err).Error("could not write response message")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-28 16:44:41 +00:00
|
|
|
// WriteError writes the error by manipulating headers and the body of the final response.
|
2023-08-18 14:29:40 +00:00
|
|
|
func WriteError(w http.ResponseWriter, errJson HasStatusCode) {
|
2023-03-28 16:44:41 +00:00
|
|
|
j, err := json.Marshal(errJson)
|
|
|
|
if err != nil {
|
|
|
|
log.WithError(err).Error("Could not marshal error message")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
w.Header().Set("Content-Length", strconv.Itoa(len(j)))
|
2023-08-18 14:29:40 +00:00
|
|
|
w.Header().Set("Content-Type", jsonMediaType)
|
|
|
|
w.WriteHeader(errJson.StatusCode())
|
2023-03-28 16:44:41 +00:00
|
|
|
if _, err := io.Copy(w, io.NopCloser(bytes.NewReader(j))); err != nil {
|
|
|
|
log.WithError(err).Error("Could not write error message")
|
|
|
|
}
|
|
|
|
}
|