certificates/api/utils.go

58 lines
1.3 KiB
Go
Raw Normal View History

2018-10-05 21:48:36 +00:00
package api
import (
"encoding/json"
"net/http"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"github.com/smallstep/certificates/api/log"
2018-10-05 21:48:36 +00:00
)
// JSON writes the passed value into the http.ResponseWriter.
func JSON(w http.ResponseWriter, v interface{}) {
2019-05-27 00:41:10 +00:00
JSONStatus(w, v, http.StatusOK)
}
// JSONStatus writes the given value into the http.ResponseWriter and the
// given status is written as the status code of the response.
func JSONStatus(w http.ResponseWriter, v interface{}, status int) {
2018-10-05 21:48:36 +00:00
w.Header().Set("Content-Type", "application/json")
2019-05-27 00:41:10 +00:00
w.WriteHeader(status)
2018-10-05 21:48:36 +00:00
if err := json.NewEncoder(w).Encode(v); err != nil {
log.Error(w, err)
2019-05-27 00:41:10 +00:00
return
2018-10-05 21:48:36 +00:00
}
log.EnabledResponse(w, v)
2018-10-05 21:48:36 +00:00
}
// ProtoJSON writes the passed value into the http.ResponseWriter.
func ProtoJSON(w http.ResponseWriter, m proto.Message) {
ProtoJSONStatus(w, m, http.StatusOK)
}
// ProtoJSONStatus writes the given value into the http.ResponseWriter and the
// given status is written as the status code of the response.
func ProtoJSONStatus(w http.ResponseWriter, m proto.Message, status int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
b, err := protojson.Marshal(m)
if err != nil {
log.Error(w, err)
return
}
if _, err := w.Write(b); err != nil {
log.Error(w, err)
return
}
// log.EnabledResponse(w, v)
}