2024-03-11 12:39:52 +00:00
|
|
|
package types
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2024-06-12 14:49:44 +01:00
|
|
|
"database/sql/driver"
|
2024-03-11 12:39:52 +00:00
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"golang.org/x/text/language"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
_ sql.Scanner = &UserLocale{}
|
2024-06-12 14:49:44 +01:00
|
|
|
_ driver.Valuer = &UserLocale{}
|
2024-03-11 12:39:52 +00:00
|
|
|
_ 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
|
|
|
|
}
|
2024-06-12 14:49:44 +01:00
|
|
|
|
|
|
|
func (l UserLocale) Value() (driver.Value, error) {
|
|
|
|
return l.Tag.String(), nil
|
|
|
|
}
|
|
|
|
|
2024-03-11 12:39:52 +00:00
|
|
|
func (l UserLocale) MarshalJSON() ([]byte, error) { return json.Marshal(l.Tag.String()) }
|
2024-06-12 14:49:44 +01:00
|
|
|
|
2024-03-11 12:39:52 +00:00
|
|
|
func (l *UserLocale) UnmarshalJSON(bytes []byte) error {
|
|
|
|
var a string
|
|
|
|
err := json.Unmarshal(bytes, &a)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return l.Scan(a)
|
|
|
|
}
|