-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrite-json.go
46 lines (38 loc) · 1.08 KB
/
write-json.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
// Copyright (c) 2024, Roel Schut. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package serv
import (
"encoding/json"
"net/http"
"github.com/go-pogo/errors"
)
const contentTypeJSON = "application/json"
// WriteJSON encodes v to JSON and writes it to w.
func WriteJSON(w http.ResponseWriter, v any) error {
if v == nil {
return nil
}
if m, ok := v.(json.Marshaler); ok {
b, err := m.MarshalJSON()
if err != nil {
return errors.WithStack(err)
}
_, _ = w.Write(b)
} else if err := json.NewEncoder(w).Encode(v); err != nil {
return errors.WithStack(err)
}
w.Header().Set("Content-Type", contentTypeJSON)
return nil
}
// WriteJSONError encodes error err to JSON and writes it to w.
func WriteJSONError(w http.ResponseWriter, err error) error {
type Error struct {
Error string `json:"error"`
}
if writeErr := WriteJSON(w, Error{err.Error()}); writeErr != nil {
return errors.WithStack(writeErr)
}
w.WriteHeader(errors.GetStatusCodeOr(err, http.StatusInternalServerError))
return nil
}