mirror of
https://github.com/1f349/tulip.git
synced 2024-11-09 22:42:53 +00:00
39 lines
765 B
Go
39 lines
765 B
Go
package types
|
|
|
|
import (
|
|
"database/sql"
|
|
"encoding/json"
|
|
"fmt"
|
|
"golang.org/x/text/language"
|
|
)
|
|
|
|
var (
|
|
_ sql.Scanner = &UserLocale{}
|
|
_ json.Marshaler = &UserLocale{}
|
|
_ json.Unmarshaler = &UserLocale{}
|
|
)
|
|
|
|
type UserLocale struct{ language.Tag }
|
|
|
|
func (l *UserLocale) Scan(src any) error {
|
|
s, ok := src.(string)
|
|
if !ok {
|
|
return fmt.Errorf("unsupported Scan, storing driver.Value type %T into type %T", src, l)
|
|
}
|
|
lang, err := language.Parse(s)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
l.Tag = lang
|
|
return nil
|
|
}
|
|
func (l UserLocale) MarshalJSON() ([]byte, error) { return json.Marshal(l.Tag.String()) }
|
|
func (l *UserLocale) UnmarshalJSON(bytes []byte) error {
|
|
var a string
|
|
err := json.Unmarshal(bytes, &a)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return l.Scan(a)
|
|
}
|