Improves documentation: Explain how to create a custom stanza extension

This commit is contained in:
Mickael Remond
2019-06-28 16:19:09 +02:00
parent 0fd1bb2483
commit e3c0747cbb
3 changed files with 86 additions and 0 deletions

View File

@@ -0,0 +1,5 @@
# Custom Stanza example
This module show how to implement a custom extension for your own client, without having to modify or fork Fluux XMPP.
It help integrating your custom extension in the standard stream parsing, marshalling and unmarshalling workflow.

View File

@@ -0,0 +1,49 @@
package main
import (
"encoding/xml"
"fmt"
"log"
"gosrc.io/xmpp/stanza"
)
func main() {
iq := stanza.NewIQ(stanza.Attrs{Type: stanza.IQTypeGet, To: "service.localhost", Id: "custom-pl-1"})
payload := CustomPayload{XMLName: xml.Name{Space: "my:custom:payload", Local: "query"}, Node: "test"}
iq.Payload = payload
data, err := xml.Marshal(iq)
if err != nil {
log.Fatalf("Cannot marshal iq with custom payload: %s", err)
}
var parsedIQ stanza.IQ
if err = xml.Unmarshal(data, &parsedIQ); err != nil {
log.Fatalf("Cannot unmarshal(%s): %s", data, err)
}
parsedPayload, ok := parsedIQ.Payload.(*CustomPayload)
if !ok {
log.Fatalf("Incorrect payload type: %#v", parsedIQ.Payload)
}
fmt.Printf("Parsed Payload: %#v", parsedPayload)
if parsedPayload.Node != "test" {
log.Fatalf("Incorrect node value: %s", parsedPayload.Node)
}
}
type CustomPayload struct {
XMLName xml.Name `xml:"my:custom:payload query"`
Node string `xml:"node,attr,omitempty"`
}
func (c CustomPayload) Namespace() string {
return c.XMLName.Space
}
func init() {
stanza.TypeRegistry.MapExtension(stanza.PKTIQ, xml.Name{"my:custom:payload", "query"}, CustomPayload{})
}