From e9d404adb184c1ac8be5f00054b5edc8f7b2309d Mon Sep 17 00:00:00 2001 From: Fenny Date: Mon, 27 Jan 2020 14:28:43 -0500 Subject: [PATCH] Add .Xml() --- docs/context.md | 23 +++++++++++++++++++++++ response.go | 12 ++++++++++++ 2 files changed, 35 insertions(+) diff --git a/docs/context.md b/docs/context.md index 19f8634a..11845989 100644 --- a/docs/context.md +++ b/docs/context.md @@ -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 + // => John50 + +}) +app.Listen(8080) + +``` + *Caught a mistake? [Edit this page on GitHub!](https://github.com/Fenny/fiber/blob/master/docs/context.md)* diff --git a/response.go b/response.go index 1c9e985a..dfe26ad9 100644 --- a/response.go +++ b/response.go @@ -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 +}