| 1 |
package types |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/json" |
| 5 |
"errors" |
| 6 |
"fmt" |
| 7 |
"net/url" |
| 8 |
) |
| 9 |
|
| 10 |
type URL struct { |
| 11 |
*url.URL |
| 12 |
} |
| 13 |
|
| 14 |
func NewURL(u string) (URL, error) { |
| 15 |
if u == "" { |
| 16 |
return URL{}, errors.New("empty URL") |
| 17 |
} |
| 18 |
|
| 19 |
stdURL, err := url.Parse(u) |
| 20 |
if err != nil { |
| 21 |
return URL{}, fmt.Errorf("failed to parse URL: %w", err) |
| 22 |
} |
| 23 |
|
| 24 |
return URL{stdURL}, nil |
| 25 |
} |
| 26 |
|
| 27 |
// IsEmpty checks if the URL is empty. |
| 28 |
// |
| 29 |
//goland:noinspection GoMixedReceiverTypes |
| 30 |
func (u *URL) IsEmpty() bool { |
| 31 |
return u == nil || u.URL == nil || u.URL.String() == "" |
| 32 |
} |
| 33 |
|
| 34 |
// String returns the string representation of the URL. |
| 35 |
// |
| 36 |
//goland:noinspection GoMixedReceiverTypes |
| 37 |
func (u URL) String() string { |
| 38 |
if u.IsEmpty() { |
| 39 |
return "" |
| 40 |
} |
| 41 |
|
| 42 |
return u.URL.String() |
| 43 |
} |
| 44 |
|
| 45 |
// MarshalText implements [encoding.TextMarshaler] interface. |
| 46 |
// |
| 47 |
//goland:noinspection GoMixedReceiverTypes |
| 48 |
func (u URL) MarshalText() ([]byte, error) { |
| 49 |
return []byte(u.String()), nil |
| 50 |
} |
| 51 |
|
| 52 |
// UnmarshalText implements the [encoding.TextUnmarshaler] interface. |
| 53 |
// |
| 54 |
//goland:noinspection GoMixedReceiverTypes |
| 55 |
func (u *URL) UnmarshalText(text []byte) error { |
| 56 |
parsedURL, err := NewURL(string(text)) |
| 57 |
if err != nil { |
| 58 |
return err |
| 59 |
} |
| 60 |
|
| 61 |
*u = parsedURL |
| 62 |
|
| 63 |
return nil |
| 64 |
} |
| 65 |
|
| 66 |
// MarshalJSON implements the [json.Marshaler] interface. |
| 67 |
// |
| 68 |
//goland:noinspection GoMixedReceiverTypes |
| 69 |
func (u *URL) MarshalJSON() ([]byte, error) { |
| 70 |
return json.Marshal(u.String()) //nolint:wrapcheck |
| 71 |
} |