types: add StrInt64 type for unmarshalling integer in string

This commit is contained in:
c9s 2023-05-18 17:32:15 +08:00
parent 10311f5c93
commit d7183cb38f
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54

38
pkg/types/strint.go Normal file
View File

@ -0,0 +1,38 @@
package types
import (
"encoding/json"
"fmt"
"strconv"
)
type StrInt64 int64
func (s *StrInt64) UnmarshalJSON(body []byte) error {
var arg interface{}
if err := json.Unmarshal(body, &arg); err != nil {
return err
}
switch ta := arg.(type) {
case string:
// parse string
i, err := strconv.ParseInt(ta, 10, 64)
if err != nil {
return err
}
*s = StrInt64(i)
case int64:
*s = StrInt64(ta)
case int32:
*s = StrInt64(ta)
case int:
*s = StrInt64(ta)
default:
return fmt.Errorf("StrInt64 error: unsupported value type %T", ta)
}
return nil
}