Add .Xml()

pull/6/head
Fenny 2020-01-27 14:28:43 -05:00
parent 8f8b394aaf
commit e9d404adb1
2 changed files with 35 additions and 0 deletions

View File

@ -1032,4 +1032,27 @@ app.Get("/", func(c *fiber.Ctx) {
})
```
#### Xml
Xml sets the header to "application/xml" and marshals your interface to xml.
```go
// Function signature
c.Xml(xml interface{}) error
// Example
type person struct {
Name string `xml:"name"`
Stars int `xml:"stars"`
}
app := fiber.New()
app.Get("/", func(c *fiber.Ctx) {
c.Xml(person{"John", 50})
// => Content-Type: application/xml
// => <person><name>John</name><stars>50</stars></person>
})
app.Listen(8080)
```
*Caught a mistake? [Edit this page on GitHub!](https://github.com/Fenny/fiber/blob/master/docs/context.md)*

View File

@ -7,6 +7,7 @@
package fiber
import (
"encoding/xml"
"fmt"
"mime"
"path/filepath"
@ -322,3 +323,14 @@ func (ctx *Ctx) Write(args ...interface{}) {
panic("body must be a string or []byte")
}
}
// Xml : https://gofiber.github.io/fiber/#/context?id=xml
func (ctx *Ctx) Xml(v interface{}) error {
raw, err := xml.Marshal(v)
if err != nil {
return err
}
ctx.Set("Content-Type", "application/xml")
ctx.Fasthttp.Response.SetBody(raw)
return nil
}