This fills the gap for nullable strings returned by the API. Signed-off-by: Yonah <contrib@gensokyo.uk>
64 lines
1.2 KiB
Go
64 lines
1.2 KiB
Go
package monstersirenfetch
|
|
|
|
import (
|
|
"encoding/json"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// Response is a generic API response.
|
|
type Response[T any] struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"msg"`
|
|
Data T `json:"data"`
|
|
}
|
|
|
|
// NullableString is a JSON string where its zero value behaves like null.
|
|
type NullableString string
|
|
|
|
func (s *NullableString) MarshalJSON() ([]byte, error) {
|
|
if *s == "" {
|
|
return []byte("null"), nil
|
|
}
|
|
return json.Marshal(string(*s))
|
|
}
|
|
|
|
func (s *NullableString) UnmarshalJSON(data []byte) (err error) {
|
|
var v *string
|
|
err = json.Unmarshal(data, &v)
|
|
if err == nil {
|
|
if v != nil {
|
|
*s = NullableString(*v)
|
|
} else {
|
|
*s = ""
|
|
}
|
|
}
|
|
return
|
|
}
|
|
|
|
// StringInt is a JSON string representing an integer.
|
|
type StringInt int
|
|
|
|
func (i *StringInt) MarshalJSON() ([]byte, error) {
|
|
s := strconv.Itoa(int(*i))
|
|
if len(s) <= 4 {
|
|
s = strings.Repeat("0", 4-len(s)) + s
|
|
} else if len(s) < 6 {
|
|
s = strings.Repeat("0", 6-len(s)) + s
|
|
}
|
|
return json.Marshal(s)
|
|
}
|
|
|
|
func (i *StringInt) UnmarshalJSON(data []byte) (err error) {
|
|
var v string
|
|
err = json.Unmarshal(data, &v)
|
|
if err == nil {
|
|
var n int
|
|
n, err = strconv.Atoi(v)
|
|
if err == nil {
|
|
*i = StringInt(n)
|
|
}
|
|
}
|
|
return
|
|
}
|