Repository navigation
Expand file tree
/
Copy pathjson.go
More file actions
83 lines (68 loc) · 1.8 KB
/
Copy pathjson.go
File metadata and controls
83 lines (68 loc) · 1.8 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"encoding/json"
"fmt"
"io"
)
// Error codes classify runtime and usage failures in JSON responses.
const (
errorCodeRuntime = "runtime_error"
errorCodeUsage = "usage_error"
)
// errorPayload wraps a JSON error response body.
type errorPayload struct {
Error errorBody `json:"error"`
}
// errorBody describes a machine-readable CLI error.
type errorBody struct {
Code string `json:"code"`
Message string `json:"message"`
}
// Mutation operation names describe successful write commands.
const (
operationCellSet = "cell_set"
operationCellClear = "cell_clear"
operationRangeClear = "range_clear"
)
// mutationResult is the success payload for workbook mutations.
type mutationResult struct {
File string `json:"file"`
Operation string `json:"operation"`
Success bool `json:"success"`
}
// writeErrorJSON writes a structured error payload.
func writeErrorJSON(w io.Writer, code, message string, pretty bool) error {
payload := errorPayload{
Error: errorBody{
Code: code,
Message: message,
},
}
return writeJSON(w, payload, pretty)
}
// writeJSON writes a JSON payload with a trailing newline.
func writeJSON(w io.Writer, payload any, pretty bool) error {
jsonBytes, err := marshalJSON(payload, pretty)
if err != nil {
return fmt.Errorf("marshal json: %w", err)
}
if _, err = w.Write(jsonBytes); err != nil {
return fmt.Errorf("write json: %w", err)
}
return nil
}
// marshalJSON encodes a payload as compact or pretty JSON.
func marshalJSON(payload any, pretty bool) ([]byte, error) {
if pretty {
jsonBytes, err := json.MarshalIndent(payload, "", " ")
if err != nil {
return nil, err
}
return append(jsonBytes, '\n'), nil
}
jsonBytes, err := json.Marshal(payload)
if err != nil {
return nil, err
}
return append(jsonBytes, '\n'), nil
}