forked from go-gorm/datatypes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
url.go
66 lines (56 loc) · 1.04 KB
/
url.go
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package datatypes
import (
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"net/url"
"strings"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
type URL url.URL
func (u URL) Value() (driver.Value, error) {
return u.String(), nil
}
func (u *URL) Scan(value interface{}) error {
var us string
switch v := value.(type) {
case []byte:
us = string(v)
case string:
us = v
default:
return errors.New(fmt.Sprint("Failed to parse URL:", value))
}
uu, err := url.Parse(us)
if err != nil {
return err
}
*u = URL(*uu)
return nil
}
func (URL) GormDataType() string {
return "url"
}
func (URL) GormDBDataType(db *gorm.DB, field *schema.Field) string {
return "TEXT"
}
func (u *URL) String() string {
return (*url.URL)(u).String()
}
func (u URL) MarshalJSON() ([]byte, error) {
return json.Marshal(u.String())
}
func (u *URL) UnmarshalJSON(data []byte) error {
// ignore null
if string(data) == "null" {
return nil
}
uu, err := url.Parse(strings.Trim(string(data), `"'`))
if err != nil {
return err
}
*u = URL(*uu)
return nil
}