Skip to content

Instantly share code, notes, and snippets.

@TheDevMinerTV
Last active July 18, 2023 19:34
Show Gist options
  • Save TheDevMinerTV/320a49b92262aeba7f95ff9c134fc536 to your computer and use it in GitHub Desktop.
Save TheDevMinerTV/320a49b92262aeba7f95ff9c134fc536 to your computer and use it in GitHub Desktop.
Multi-encoding response in Golang with fiber
package main
import (
"github.com/gofiber/fiber/v2"
)
type SomethingDto struct {
ID int `json:"id" xml:"id" protobuf:"int,1,opt,name=id"`
}
func somethingAPI(c *fiber.Ctx) (*SomethingDto, error) {
return &SomethingDto{ID: 1}, nil
}
func encode[T any](c *fiber.Ctx, res T, accepts string) err {
switch accepts {
case "application/json":
return c.JSON(res)
case "application/x-protobuf":
// TODO: encode as protobuf
return c.SendString("TODO")
case "application/xml":
return c.XML(res)
}
}
func wrap[T any](handler func(c *fiber.Ctx) (T, error)) func(c *fiber.Ctx) error {
return func(c *fiber.Ctx) error {
accepts := c.Accepts("application/json", "application/x-protobuf", "application/xml")
if accepts == "" {
return c.SendStatus(fiber.StatusNotAcceptable)
}
res, err := handler(c)
if err != nil {
// Just make sure you actually return data, otherwise this will panic
return encode(c, res, accepts)
}
return encode(c, res, accepts)
}
}
func main() {
app := fiber.New()
app.Get("/api/something", wrap(somethingAPI))
if err := app.Listen(":3000"); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment