-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoding.go
50 lines (40 loc) · 978 Bytes
/
encoding.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
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type responseError struct {
Ok bool `json:"ok"`
Error string `json:"error"`
}
func encodeError(w http.ResponseWriter, status int, e string) error {
return encode(w, status, responseError{Ok: false, Error: e})
}
func encodeOK[T any](w http.ResponseWriter, v T) error {
return encode(w, http.StatusOK, struct {
Ok bool `json:"ok"`
Data T `json:"data,omitempty"`
}{
Ok: true,
Data: v,
})
}
func encode(w http.ResponseWriter, status int, v any) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
err := json.NewEncoder(w).Encode(v)
if err != nil {
return fmt.Errorf("encode json: %w", err)
}
return nil
}
// decodes the given struct as JSON from the request body
func decode[T any](r *http.Request) (T, error) {
var v T
err := json.NewDecoder(r.Body).Decode(&v)
if err != nil {
return v, fmt.Errorf("decode json: %w", err)
}
return v, nil
}