Skip to content

Commit

Permalink
message: implement String()
Browse files Browse the repository at this point in the history
This provides a convenient way to visualize message data when debugging,
logging, etc. While the format is inspired by swanctl.conf, String() is
not guaranteed to produce valid output for use in swanctl.conf directly.

Exercise this new method in the message_test.go examples.
  • Loading branch information
enr0n committed Feb 25, 2025
1 parent ce0059d commit d5f0350
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 11 deletions.
24 changes: 24 additions & 0 deletions vici/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,30 @@ func (m *Message) Err() error {
return nil
}

func (m *Message) stringIndent(prefix, indent string) string {
var str string

for k, v := range m.elements() {
switch v := v.(type) {
case string:
str += fmt.Sprintf("%s%s%s = %s\n", prefix, indent, k, v)
case []string:
str += fmt.Sprintf("%s%s%s = %s\n", prefix, indent, k, strings.Join(v, ","))
case *Message:
str += fmt.Sprintf("%s%s%s %s", prefix, indent, k, v.stringIndent(prefix+indent, indent))
}
}
str = fmt.Sprintf("{\n%s%s}\n", str, prefix)

return str
}

// String returns the string form of m. For readability, the output format is similar to
// swanctl.conf configuration format.
func (m *Message) String() string {
return m.stringIndent("", " ")
}

// packetIsNamed returns a bool indicating the packet is a named type
func (m *Message) packetIsNamed() bool {
if m.header == nil {
Expand Down
38 changes: 27 additions & 11 deletions vici/message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -333,16 +333,28 @@ func ExampleMarshalMessage() {
return
}

fmt.Println(m.Get("proposals"))
fmt.Println(m)
// Output: {
// local_addrs = 192.168.0.1
// local {
// auth = pubkey
// certs = moonCert.pem
// id = moon.strongswan.org
// }
// remote {
// auth = pubkey
// }
// children {
// net {
// local_ts = 10.1.0.0/16
// updown = /usr/local/libexec/ipsec/_updown iptables
// esp_proposals = aes128gcm128-x25519
// }
// }
// version = 2
// proposals = aes128-sha256-x25519
// }

net := m.Get("children").(*Message).Get("net").(*Message)
for _, k := range net.Keys() {
fmt.Printf("%s: %s\n", k, net.Get(k))
}
// Output: [aes128-sha256-x25519]
// local_ts: [10.1.0.0/16]
// updown: /usr/local/libexec/ipsec/_updown iptables
// esp_proposals: [aes128gcm128-x25519]
}

func ExampleUnmarshalMessage() {
Expand Down Expand Up @@ -737,8 +749,12 @@ func ExampleMessage_Set() {
return
}

fmt.Printf("%v, %v, %v\n", m.Get("version"), m.Get("mobike"), m.Get("local_addrs"))
// Output: 2, no, [192.168.0.1/24]
fmt.Println(m)
// Output: {
// version = 2
// mobike = no
// local_addrs = 192.168.0.1/24
// }
}

func TestEmptyMessageElement(t *testing.T) {
Expand Down

0 comments on commit d5f0350

Please sign in to comment.