-
Notifications
You must be signed in to change notification settings - Fork 9
/
types.go
62 lines (52 loc) · 1.15 KB
/
types.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
package ssi
import (
"encoding"
"encoding/json"
"fmt"
"net/url"
)
var _ encoding.TextMarshaler = URI{}
var _ json.Marshaler = URI{}
var _ json.Unmarshaler = &URI{}
var _ fmt.Stringer = URI{}
// URI is a wrapper around url.URL to add json marshalling
type URI struct {
url.URL
}
// MarshalText implements encoding.TextMarshaler
func (v URI) MarshalText() ([]byte, error) {
return []byte(v.String()), nil
}
func (v URI) MarshalJSON() ([]byte, error) {
return json.Marshal(v.String())
}
func (v *URI) UnmarshalJSON(bytes []byte) error {
var value string
if err := json.Unmarshal(bytes, &value); err != nil {
return err
}
parsedUrl, err := url.Parse(value)
if err != nil {
return fmt.Errorf("could not parse URI: %w", err)
}
v.URL = *parsedUrl
return nil
}
// ParseURI parses a raw URI. If it can't be parsed, an error is returned.
func ParseURI(input string) (*URI, error) {
u, err := url.Parse(input)
if err != nil {
return nil, err
}
return &URI{URL: *u}, nil
}
func MustParseURI(input string) URI {
u, err := url.Parse(input)
if err != nil {
panic(err)
}
return URI{URL: *u}
}
func (v URI) String() string {
return v.URL.String()
}