Gin: How to render XML attributes?

Created on 10 Jun 2015  路  6Comments  路  Source: gin-gonic/gin

I'm using a website's REST API and they require me to send a XML as response! I checked out their documentation, and found out this:

<Response>
    <Message src="12023222222" dst="15671234567" type="sms"
            callbackUrl="http://foo.com/sms_status/" callbackMethod="POST">
    Hi, Message from Plivo
    </Message>
</Response>

Is there anyway to specify or attach attributes using gin's renderer?
I also found this library: https://github.com/unrolled/render, which claims that they use Martini's renderer. Could this library work with Gin as well?

Most helpful comment

@windweller I recommend you to avoid using that external render since it does not have any advantage.

Gin already provides well tested and optimized methods (using the standard library)

type ExampleXml struct {
    XMLName xml.Name `xml:"example"`
    One     string   `xml:"one,attr"`
    Two     string   `xml:"two,attr"`
}

func handler(c *gin.Context) {
    c.XML(http.StatusOK, ExampleXml{One: "hello", Two: "xml"})
}

you do not need external packages.

All 6 comments

Yes it works with Gin, it even has examples in the README on how to use it with Gin.
https://github.com/unrolled/render#gin

LOL did not read it that far, THANKS!

Does Gin render XML attributes by default though?

Yes it does (https://github.com/gin-gonic/gin/blob/master/render/xml.go) it uses the Go stdlib to do so.
Examples from README https://github.com/gin-gonic/gin#xml-and-json-rendering

@windweller I recommend you to avoid using that external render since it does not have any advantage.

Gin already provides well tested and optimized methods (using the standard library)

type ExampleXml struct {
    XMLName xml.Name `xml:"example"`
    One     string   `xml:"one,attr"`
    Two     string   `xml:"two,attr"`
}

func handler(c *gin.Context) {
    c.XML(http.StatusOK, ExampleXml{One: "hello", Two: "xml"})
}

you do not need external packages.

Thank you @manucorporat !

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mastrolinux picture mastrolinux  路  3Comments

oryband picture oryband  路  3Comments

gplume picture gplume  路  3Comments

Bloomca picture Bloomca  路  3Comments

mdnight picture mdnight  路  3Comments