-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrespond.go
More file actions
30 lines (24 loc) · 768 Bytes
/
respond.go
File metadata and controls
30 lines (24 loc) · 768 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package platform
import (
"encoding/json"
"net/http"
"github.com/titpetric/platform/pkg/telemetry"
)
// JSON writes any payload as JSON. If the payload is nil, the write is omitted.
// If an error occurs in encoding, a telemetry error is logged.
func JSON(w http.ResponseWriter, r *http.Request, status int, data any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if data != nil {
telemetry.CaptureError(r.Context(), json.NewEncoder(w).Encode(data))
}
}
// Error writes an error payload as JSON.
func Error(w http.ResponseWriter, r *http.Request, status int, data error) {
var response ErrorResponse
response.Error.Code = status
if data != nil {
response.Error.Message = data.Error()
}
JSON(w, r, status, response)
}