This chapter introduces how Go Fiber handles request and response, typically by returning JSON data for current API development.

The Fiber framework primarily uses the return data of the Ctx context object.

Returning JSON Data

type SomeStruct struct {
  Name string
  Age  uint8
}

app.Get("/json", func(c *fiber.Ctx) error {
  // Create data struct for response
  data := SomeStruct{
    Name: "Grame",
    Age:  20,
  }

  // Return using the json function
  return c.JSON(data)
  // => Content-Type: application/json
  // => "{"Name": "Grame", "Age": 20}"

  return c.JSON(fiber.Map{
    "name": "Grame",
    "age": 20,
  })
  // => Content-Type: application/json
  // => "{"name": "Grame", "age": 20}"
})

Returning JSONP Format

type SomeStruct struct {
  name string
  age  uint8
}

app.Get("/", func(c *fiber.Ctx) error {
  // Create data struct
  data := SomeStruct{
    name: "Grame",
    age:  20,
  }

  return c.JSONP(data)
  // => callback({"name": "Grame", "age": 20})

  return c.JSONP(data, "customFunc")
  // => customFunc({"name": "Grame", "age": 20})
})

Returning Text

app.Get("/", func(c *fiber.Ctx) error {
        // Return "Hello, World ?!" as a string
        return c.SendString("Hello, World ?!")
})

Returning Status Code

app.Get("/not-found", func(c *fiber.Ctx) error {
  // Set the response status code
  return c.SendStatus(415)
  // => 415 "Unsupported Media Type"

  c.SendString("Hello, World!")
  // Set the response status code
  return c.SendStatus(415)
  // => 415 "Hello, World!"
})

Returning Files (Implement File Download)

app.Get("/", func(c *fiber.Ctx) error {
  return c.Download("./files/report-12345.pdf");
  // => Download report-12345.pdf

  return c.Download("./files/report-12345.pdf", "report.pdf");
  // => Download report.pdf
})

Setting Request Headers

app.Get("/", func(c *fiber.Ctx) error {
  c.Set("Content-Type", "text/plain")
  // => "Content-type: text/plain"

  // ...
})

Setting Cookies

Cookie definition

type Cookie struct {
    Name        string    `json:"name"`
    Value       string    `json:"value"`
    Path        string    `json:"path"`
    Domain      string    `json:"domain"`
    MaxAge      int       `json:"max_age"`
    Expires     time.Time `json:"expires"`
    Secure      bool      `json:"secure"`
    HTTPOnly    bool      `json:"http_only"`
    SameSite    string    `json:"same_site"`
    SessionOnly bool      `json:"session_only"`
}

Returning Cookie

app.Get("/", func(c *fiber.Ctx) error {
  // Create cookie
  cookie := new(fiber.Cookie)
  cookie.Name = "john"
  cookie.Value = "doe"
  cookie.Expires = time.Now().Add(24 * time.Hour)

  // Set cookie
  c.Cookie(cookie)
  // ...
})

Redirect (301 or 302)

Default is a 302 redirect

app.Get("/", func(c *fiber.Ctx) error {
  return c.Redirect("/foo/bar")
  return c.Redirect("../login")
  return c.Redirect("http://example.com")
  return c.Redirect("http://example.com", 301)
})