rproxy3/storage/packable/packable.go

76 lines
1.1 KiB
Go
Executable File

package packable
import (
"bytes"
"encoding/gob"
"net/url"
)
type Packable interface {
Encode() ([]byte, error)
Decode([]byte) error
}
type String string
func (s *String) String() string {
return string(*s)
}
func (s *String) Encode() ([]byte, error) {
return []byte(*s), nil
}
func (s *String) Decode(b []byte) error {
*s = String(string(b))
return nil
}
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,
}
}