2018-10-05 21:48:36 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
|
2021-05-03 19:48:20 +00:00
|
|
|
"google.golang.org/protobuf/encoding/protojson"
|
|
|
|
"google.golang.org/protobuf/proto"
|
2022-03-18 13:25:34 +00:00
|
|
|
|
2022-03-22 12:31:18 +00:00
|
|
|
"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 {
|
2022-03-22 12:31:18 +00:00
|
|
|
log.Error(w, err)
|
|
|
|
|
2019-05-27 00:41:10 +00:00
|
|
|
return
|
2018-10-05 21:48:36 +00:00
|
|
|
}
|
2022-03-22 12:31:18 +00:00
|
|
|
|
|
|
|
log.EnabledResponse(w, v)
|
2018-10-05 21:48:36 +00:00
|
|
|
}
|
|
|
|
|
2021-05-03 19:48:20 +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 {
|
2022-03-22 12:31:18 +00:00
|
|
|
log.Error(w, err)
|
|
|
|
|
2021-05-03 19:48:20 +00:00
|
|
|
return
|
|
|
|
}
|
2022-03-22 12:31:18 +00:00
|
|
|
|
2021-05-03 19:48:20 +00:00
|
|
|
if _, err := w.Write(b); err != nil {
|
2022-03-22 12:31:18 +00:00
|
|
|
log.Error(w, err)
|
|
|
|
|
2021-05-03 19:48:20 +00:00
|
|
|
return
|
|
|
|
}
|
2022-03-22 12:31:18 +00:00
|
|
|
|
|
|
|
// log.EnabledResponse(w, v)
|
2021-05-03 19:48:20 +00:00
|
|
|
}
|