Skip to content

Commit

Permalink
kv:fixes bugs and added tests
Browse files Browse the repository at this point in the history
  • Loading branch information
axfor committed Feb 6, 2020
1 parent d2d665a commit d15c325
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 11 deletions.
34 changes: 23 additions & 11 deletions kv/kv.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,32 +25,36 @@ func New() Any {

//URL returns k1=v1&k2=v2
func (c *Any) URL() string {
return c.Join("&")
}

//Join returns e.g k1=v1&k2=v2
func (c *Any) Join(sep string) string {
if sep == "" {
sep = "&"
}
var s []string
ks, vs := "", ""
var ser Stringer
ok := false
for k, v := range *c {
if k != nil && v != nil {
ks, vs = "", ""
ser, ok = k.(Stringer)
if !ok {
ks = ser.String()
if tv, ok := k.(Stringer); ok {
ks = tv.String()
} else {
ks = fmt.Sprintf("%v", k)
}
ser, ok = v.(Stringer)
if !ok {
vs = ser.String()
if tv, ok := v.(Stringer); ok {
vs = tv.String()
} else {
vs = fmt.Sprintf("%v", k)
vs = fmt.Sprintf("%v", v)
}
s = append(s, ks+"="+vs)
}
}
if s != nil {
sort.Sort(sort.StringSlice(s))
}
return strings.Join(s, "&")
return strings.Join(s, sep)
}

//String KV for string
Expand All @@ -64,6 +68,14 @@ func NewString() String {

//URL returns k1=v1&k2=v2
func (c *String) URL() string {
return c.Join("&")
}

//Join returns e.g k1=v1&k2=v2
func (c *String) Join(sep string) string {
if sep == "" {
sep = "&"
}
var s []string
for k, v := range *c {
if k != "" && v != "" {
Expand All @@ -73,5 +85,5 @@ func (c *String) URL() string {
if s != nil {
sort.Sort(sort.StringSlice(s))
}
return strings.Join(s, "&")
return strings.Join(s, sep)
}
37 changes: 37 additions & 0 deletions kv/kv_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package kv

import "testing"

func Test_Any(t *testing.T) {
v := New()
v["name"] = "111"
v["age"] = 18
v["sex"] = "girl"
v["node"] = "bast"
s := v.URL()
if s != "age=18&name=111&node=bast&sex=girl" {
t.Fail()
}
s2 := v.Join("&")
if s != s2 {
t.Fail()
}

t.Log(s2)
}

func Test_String(t *testing.T) {
v := NewString()
v["name"] = "111"
v["age"] = "18"
v["sex"] = "girl"
v["node"] = "bast"
s := v.URL()
if s != "age=18&name=111&node=bast&sex=girl" {
t.Fail()
}
s2 := v.Join("&")
if s != s2 {
t.Fail()
}
}

0 comments on commit d15c325

Please sign in to comment.