-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
68 lines (52 loc) · 1.37 KB
/
response.go
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package von
import (
"context"
"encoding/json"
"net/http"
"github.com/pkg/errors"
"go.opentelemetry.io/otel/trace"
)
// Respond converts a Go value to JSON and sends it to the client.
func Respond(ctx context.Context, w http.ResponseWriter, data interface{}, statusCode int) error {
ctx, span := trace.SpanFromContext(ctx).Tracer().Start(ctx, "von.respond")
defer span.End()
v, ok := ctx.Value(KeyValues).(*Values)
if !ok {
return NewShutdownError("web value missing from context")
}
v.Status = statusCode
if statusCode == http.StatusNoContent {
w.WriteHeader(statusCode)
return nil
}
jsonData, err := json.Marshal(data)
if err != nil {
return err
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
if _, err := w.Write(jsonData); err != nil {
return err
}
return nil
}
// RespondError sends an error response back to the client
func RespondError(ctx context.Context, w http.ResponseWriter, err error) error {
if webErr, ok := errors.Cause(err).(*Error); ok {
er := ErrorResponse{
Error: webErr.Err.Error(),
Fields: webErr.Fields,
}
if err := Respond(ctx, w, er, webErr.Status); err != nil {
return err
}
return nil
}
er := ErrorResponse{
Error: http.StatusText(http.StatusInternalServerError),
}
if err := Respond(ctx, w, er, http.StatusInternalServerError); err != nil {
return err
}
return nil
}