|
|
@@ -2,52 +2,14 @@ package api
|
|
|
|
|
|
import (
|
|
|
"encoding/json"
|
|
|
- "log"
|
|
|
"net/http"
|
|
|
|
|
|
"google.golang.org/protobuf/encoding/protojson"
|
|
|
"google.golang.org/protobuf/proto"
|
|
|
|
|
|
- "github.com/smallstep/certificates/logging"
|
|
|
+ "github.com/smallstep/certificates/api/log"
|
|
|
)
|
|
|
|
|
|
-// EnableLogger is an interface that enables response logging for an object.
|
|
|
-type EnableLogger interface {
|
|
|
- ToLog() (interface{}, error)
|
|
|
-}
|
|
|
-
|
|
|
-// LogError adds to the response writer the given error if it implements
|
|
|
-// logging.ResponseLogger. If it does not implement it, then writes the error
|
|
|
-// using the log package.
|
|
|
-func LogError(rw http.ResponseWriter, err error) {
|
|
|
- if rl, ok := rw.(logging.ResponseLogger); ok {
|
|
|
- rl.WithFields(map[string]interface{}{
|
|
|
- "error": err,
|
|
|
- })
|
|
|
- } else {
|
|
|
- log.Println(err)
|
|
|
- }
|
|
|
-}
|
|
|
-
|
|
|
-// LogEnabledResponse log the response object if it implements the EnableLogger
|
|
|
-// interface.
|
|
|
-func LogEnabledResponse(rw http.ResponseWriter, v interface{}) {
|
|
|
- if el, ok := v.(EnableLogger); ok {
|
|
|
- out, err := el.ToLog()
|
|
|
- if err != nil {
|
|
|
- LogError(rw, err)
|
|
|
- return
|
|
|
- }
|
|
|
- if rl, ok := rw.(logging.ResponseLogger); ok {
|
|
|
- rl.WithFields(map[string]interface{}{
|
|
|
- "response": out,
|
|
|
- })
|
|
|
- } else {
|
|
|
- log.Println(out)
|
|
|
- }
|
|
|
- }
|
|
|
-}
|
|
|
-
|
|
|
// JSON writes the passed value into the http.ResponseWriter.
|
|
|
func JSON(w http.ResponseWriter, v interface{}) {
|
|
|
JSONStatus(w, v, http.StatusOK)
|
|
|
@@ -59,10 +21,12 @@ func JSONStatus(w http.ResponseWriter, v interface{}, status int) {
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
w.WriteHeader(status)
|
|
|
if err := json.NewEncoder(w).Encode(v); err != nil {
|
|
|
- LogError(w, err)
|
|
|
+ log.Error(w, err)
|
|
|
+
|
|
|
return
|
|
|
}
|
|
|
- LogEnabledResponse(w, v)
|
|
|
+
|
|
|
+ log.EnabledResponse(w, v)
|
|
|
}
|
|
|
|
|
|
// ProtoJSON writes the passed value into the http.ResponseWriter.
|
|
|
@@ -78,12 +42,16 @@ func ProtoJSONStatus(w http.ResponseWriter, m proto.Message, status int) {
|
|
|
|
|
|
b, err := protojson.Marshal(m)
|
|
|
if err != nil {
|
|
|
- LogError(w, err)
|
|
|
+ log.Error(w, err)
|
|
|
+
|
|
|
return
|
|
|
}
|
|
|
+
|
|
|
if _, err := w.Write(b); err != nil {
|
|
|
- LogError(w, err)
|
|
|
+ log.Error(w, err)
|
|
|
+
|
|
|
return
|
|
|
}
|
|
|
- //LogEnabledResponse(w, v)
|
|
|
+
|
|
|
+ // log.EnabledResponse(w, v)
|
|
|
}
|