Bläddra i källkod

beam/data: Message.GetOne() returns the last value set at a key

This is a convenience for callers which are only interested in one value
per key. Similar to how HTTP headers allow multiple keys per value, but
are often used to store and retrieve only one value.

Docker-DCO-1.1-Signed-off-by: Solomon Hykes <solomon@docker.com> (github: shykes)
Solomon Hykes 11 år sedan
förälder
incheckning
2af030ab57
2 ändrade filer med 18 tillägg och 0 borttagningar
  1. 10 0
      pkg/beam/data/message.go
  2. 8 0
      pkg/beam/data/message_test.go

+ 10 - 0
pkg/beam/data/message.go

@@ -72,6 +72,16 @@ func (m Message) Get(k string) []string {
 	return v
 	return v
 }
 }
 
 
+// GetOne returns the last value added at the key k,
+// or an empty string if there is no value.
+func (m Message) GetOne(k string) string {
+	var v string
+	if vals := m.Get(k); len(vals) > 0 {
+		v = vals[len(vals)-1]
+	}
+	return v
+}
+
 func (m Message) Pretty() string {
 func (m Message) Pretty() string {
 	data, err := Decode(string(m))
 	data, err := Decode(string(m))
 	if err != nil {
 	if err != nil {

+ 8 - 0
pkg/beam/data/message_test.go

@@ -51,3 +51,11 @@ func TestSetDelMessage(t *testing.T) {
 		t.Fatalf("'%v' != '%v'", output, expectedOutput)
 		t.Fatalf("'%v' != '%v'", output, expectedOutput)
 	}
 	}
 }
 }
+
+func TestGetOne(t *testing.T) {
+	m := Empty().Set("shadok words", "ga", "bu", "zo", "meu")
+	val := m.GetOne("shadok words")
+	if val != "meu" {
+		t.Fatalf("%#v", val)
+	}
+}