this seems okay
This commit is contained in:
@@ -1,5 +1,11 @@
|
||||
package packable
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/gob"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
type Packable interface {
|
||||
Encode() ([]byte, error)
|
||||
Decode([]byte) error
|
||||
@@ -20,7 +26,50 @@ func (s *String) Decode(b []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewString(s string) *String {
|
||||
w := String(s)
|
||||
func NewString(s ...string) *String {
|
||||
if len(s) == 0 {
|
||||
s = append(s, "")
|
||||
}
|
||||
w := String(s[0])
|
||||
return &w
|
||||
}
|
||||
|
||||
type URL struct {
|
||||
Scheme string
|
||||
Host string
|
||||
Path string
|
||||
}
|
||||
|
||||
func (u *URL) URL() *url.URL {
|
||||
return &url.URL{
|
||||
Scheme: u.Scheme,
|
||||
Host: u.Host,
|
||||
Path: u.Path,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *URL) Encode() ([]byte, error) {
|
||||
buf := bytes.NewBuffer(nil)
|
||||
g := gob.NewEncoder(buf)
|
||||
if err := g.Encode(*u); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func (u *URL) Decode(b []byte) error {
|
||||
buf := bytes.NewBuffer(b)
|
||||
g := gob.NewDecoder(buf)
|
||||
return g.Decode(&u)
|
||||
}
|
||||
|
||||
func NewURL(u ...*url.URL) *URL {
|
||||
if len(u) == 0 {
|
||||
u = append(u, &url.URL{})
|
||||
}
|
||||
return &URL{
|
||||
Scheme: u[0].Scheme,
|
||||
Host: u[0].Host,
|
||||
Path: u[0].Path,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package packable
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPackableString(t *testing.T) {
|
||||
raw := "hello"
|
||||
@@ -21,3 +24,24 @@ func TestPackableString(t *testing.T) {
|
||||
t.Errorf("wrong decoded string: %v vs %v", x, raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPackableURL(t *testing.T) {
|
||||
raw := &url.URL{
|
||||
Scheme: "a",
|
||||
Host: "b",
|
||||
Path: "c",
|
||||
}
|
||||
s := NewURL(raw)
|
||||
|
||||
packed, err := s.Encode()
|
||||
if err != nil {
|
||||
t.Errorf("cannot encode URL: %v", err)
|
||||
}
|
||||
|
||||
x := NewURL()
|
||||
if err := x.Decode(packed); err != nil {
|
||||
t.Errorf("cannot decode URL: %v", err)
|
||||
} else if *x != *s {
|
||||
t.Errorf("wrong decoded URL: %v (%T) vs %v (%T)", x, x, s, s)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user