/
api_helpers.go
51 lines (38 loc) · 1.03 KB
/
api_helpers.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
// SPDX-FileCopyrightText: 2023 Institute for Automation of Complex Power Systems
// SPDX-License-Identifier: Apache-2.0
package main
import (
"encoding/json"
"fmt"
"net/http"
"golang.org/x/exp/slog"
)
func writeJSON(w http.ResponseWriter, resp any) bool {
if err := json.NewEncoder(w).Encode(resp); err != nil {
slog.Error("Failed to encode API response",
slog.Any("error", err),
slog.Any("resp", resp))
w.WriteHeader(http.StatusInternalServerError)
return false
}
return true
}
func readJSON(w http.ResponseWriter, r *http.Request, req any) bool {
if err := json.NewDecoder(r.Body).Decode(req); err != nil {
writeError(w, http.StatusBadRequest, fmt.Errorf("failed to parse request body: %w", err))
return false
}
return true
}
func writeError(w http.ResponseWriter, code int, err error) bool {
resp := &apiErrorResponse{
Error: err.Error(),
Status: http.StatusText(code),
}
slog.Error("Request failed", slog.Any("error", err))
if writeJSON(w, resp) {
w.WriteHeader(code)
return true
}
return false
}