-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.go
More file actions
45 lines (37 loc) · 1018 Bytes
/
types.go
File metadata and controls
45 lines (37 loc) · 1018 Bytes
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
package bytesend
import (
"encoding/json"
"fmt"
)
type ErrorResponse struct {
Message string `json:"message"`
Code string `json:"code"`
}
func (e *ErrorResponse) Error() string {
return fmt.Sprintf("%s: %s", e.Code, e.Message)
}
// StringSlice unmarshals a JSON value that can be either a string or an array of strings
// into a Go []string. This accommodates API responses that may return a single string
// or multiple values interchangeably.
type StringSlice []string
func (s *StringSlice) UnmarshalJSON(b []byte) error {
// Try to unmarshal as an array of strings first
var arr []string
if err := json.Unmarshal(b, &arr); err == nil {
*s = arr
return nil
}
// Try to unmarshal as a single string
var single string
if err := json.Unmarshal(b, &single); err == nil {
*s = []string{single}
return nil
}
// Accept null as nil slice
if string(b) == "null" {
*s = nil
return nil
}
// Fallback: return original error by attempting array once more
return json.Unmarshal(b, &arr)
}