Learn Fiber Β· 3/14

The Fiber Context (*fiber.Ctx)

6 min read

The Fiber Context (*fiber.Ctx) πŸ“–

Welcome, fellow Gopher! Today, we're diving deep into the heart of the Fiber web framework: the *fiber.Ctx. If you've ever worked with a web framework, you know there's always that one object that seems to hold all the power. In Fiber, that's the Context. It's your trusty multi-tool for handling everything related to a single HTTP request. So, grab a cup of coffee β˜•, and let's get started!

1. What is Context? The Heart of Fiber ❀️

The Problem: Imagine you're a librarian at a massive, bustling library. Every person who comes in (a request) has a unique set of needs: they want a specific book (data), they have a library card (authentication), and they need to know where to go (routing). If you tried to remember every single person's details simultaneously, your brain would probably short-circuit. You need a system, a dedicated workspace for each person, to keep things organized.

The Solution: In Fiber, the *fiber.Ctx (or Context) is that dedicated workspace for each incoming HTTP request. It's a struct that holds all the information about a request and provides a suite of methods to interact with it. This is incredibly important because a web server handles many requests at the same time. The Context ensures that the information for one user's request doesn't get mixed up with another's.

Under the hood, Fiber is built on top of Fasthttp, the fastest HTTP engine for Go. To achieve its high performance, Fiber reuses Context objects for different requests to reduce memory allocation. This is a nifty performance trick, but it comes with a crucial rule: you should only use the context's values within the handler function. If you need to use a value outside of the handler, you must make a copy of it.

Here's a barebones Fiber "Hello, World!" to see the Context in action:

go
package main

import "github.com/gofiber/fiber/v2"

func main() {
    app := fiber.New()

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

    app.Listen(":3000")
}

In this example, c is our *fiber.Ctx. We use its SendString method to send a response back to the client. Simple, right? Now, let's see what else this powerful object can do.

2. Reading Query Parameters and Headers 🧐

The Problem: A client often sends extra information along with a request. This could be in the URL as query parameters (like ?search=books) or as headers (like Authorization: Bearer <token>). Your application needs a way to read this information to tailor its response. For instance, an e-commerce site might use query parameters to filter products, and an API might use headers for authentication.

The Solution: The *fiber.Ctx provides convenient methods to access both query parameters and headers.

Query Parameters

Let's say a user makes a GET request to /users?name=john&age=30. You can easily grab these values:

go
app.Get("/users", func(c *fiber.Ctx) error {
    name := c.Query("name") // "john"
    age := c.Query("age")   // "30"

    return c.SendString("Name: " + name + ", Age: " + age)
})

The Query method is your go-to for plucking individual values from the URL's query string.

Headers

Headers are just as easy to access. Imagine a client sends a request with an X-Request-ID header.

go
app.Get("/info", func(c *fiber.Ctx) error {
    requestID := c.Get("X-Request-ID")
    // The match for the header key is case-insensitive
    return c.SendString("Request ID: " + requestID)
})

The Get method allows you to retrieve the value of a specific request header. You can get all request headers as a map using c.GetReqHeaders().

3. Parsing Request Bodies: JSON, XML, and Form Data πŸ“

The Problem: For POST, PUT, and PATCH requests, the client usually sends data in the request body. This data can be in various formats, with JSON being the most common for modern APIs. Your server needs to be able to understand and parse this data into a format it can work with, like a Go struct.

The Solution: Fiber's *fiber.Ctx has a powerful BodyParser method that can automatically parse different content types, including JSON, XML, and form data, into a Go struct. This is a huge time-saver and helps keep your code clean and organized.

Let's define a User struct that we'll use for our examples:

go
type User struct {
    Name  string `json:"name" xml:"name" form:"name"`
    Email string `json:"email" xml:"email" form:"email"`
}

JSON

If a client sends a POST request with a JSON body to /users:

go
app.Post("/users", func(c *fiber.Ctx) error {
    user := new(User)

    if err := c.BodyParser(user); err != nil {
        return err
    }

    // Now you can work with the user object
    return c.JSON(fiber.Map{
        "message": "User created successfully!",
        "user":    user,
    })
})

In this snippet, c.BodyParser(user) does the heavy lifting of reading the JSON from the request body and populating the user struct.

XML

What if you're working with a system that speaks XML? Fiber has you covered. The same BodyParser can handle it, as long as the Content-Type header is application/xml.

Form Data

For traditional web forms that submit data with a Content-Type of application/x-www-form-urlencoded, BodyParser works just as seamlessly.

A note on Fiber v3's Bind(): For those using Fiber v3 or newer, there's an even more explicit and powerful way to handle data binding with c.Bind(). This provides more control and clarity by allowing you to specify the source of the data (body, query, header, etc.).

4. Working with Cookies: Read and Write πŸͺ

The Problem: Sometimes you need to store a small amount of information on the client's browser. This is what cookies were made for! They are commonly used for managing sessions, storing user preferences, and tracking user activity. Your application needs a way to both send (set) cookies to the browser and read them back on subsequent requests.

The Solution: The *fiber.Ctx makes working with cookies a piece of cake.

Writing a Cookie

To send a cookie to the client, you create a fiber.Cookie struct and pass it to the Cookie method.

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

    c.Cookie(cookie)

    return c.SendString("You are now logged in!")
})

This will set a session_id cookie in the user's browser that expires in 24 hours.

Reading a Cookie

To read a cookie that the client sends back, you use the Cookies method.

go
app.Get("/profile", func(c *fiber.Ctx) error {
    sessionID := c.Cookies("session_id")

    if sessionID == "" {
        return c.Status(fiber.StatusUnauthorized).SendString("You are not logged in.")
    }

    return c.SendString("Your session ID is: " + sessionID)
})

Here, we're checking for the session_id cookie to see if the user is "logged in."

Clearing a Cookie

To log a user out, you can clear their session cookie. One common way to do this is to set the cookie's expiration date to a time in the past.

go
app.Get("/logout", func(c *fiber.Ctx) error {
    c.ClearCookie("session_id") // This will expire the cookie
    return c.SendString("You have been logged out.")
})

There have been some discussions and improvements around ClearCookie in the Fiber community, so it's always a good idea to check the latest documentation if you encounter any issues.

And that's a wrap on our tour of the *fiber.Ctx! It's the central nervous system of your Fiber application, giving you the power to handle requests and craft responses with ease. Happy coding! πŸš€


Extra Reading & References πŸ“š

Challenge

You are tasked with creating a Fiber handler for updating a user profile. Your handler must process request data from multiple sources: headers, query parameters, and the request body.

Requirements:

  1. Define a Go struct named UserProfile. It must have two string fields: Username and FullName. Add the corresponding JSON tags (username and fullName).
  2. Implement the updateProfileHandler function.
  3. Inside the handler, perform these steps sequentially:
    • Read the value from a custom request header named X-Transaction-ID.
    • Read the value of the account_id URL query parameter.
    • Parse the incoming JSON request body into an instance of your UserProfile struct.
    • Create a new fiber.Cookie with the following properties:
      • Name: session_id
      • Value: The value read from the X-Transaction-ID header.
      • Expires: 12 hours from the current time.
    • Set this cookie in the response.
    • Respond with a JSON object. The object must have a status field with the value "success", an accountId field containing the value from the query parameter, and a profile field containing the parsed UserProfile object.

Expected result

Your solution should be a single block of Go code that defines the UserProfile struct and fully implements the updateProfileHandler function.

The final code should demonstrate the following:

  • A UserProfile struct with Username and FullName string fields, each tagged for JSON marshaling as username and fullName respectively.
  • The updateProfileHandler function must correctly use c.Get("X-Transaction-ID") to retrieve the header value.
  • It must use c.Query("account_id") to retrieve the query parameter.
  • It must use c.BodyParser() to parse the request body into a UserProfile struct instance.
  • It must correctly instantiate a fiber.Cookie with the name session_id, a value derived from the header, and an Expires property set to time.Now().Add(12 * time.Hour).
  • The created cookie must be sent to the client using the c.Cookie() method.
  • The handler must conclude by sending a JSON response using c.JSON() with a structure matching the requirements, including status, accountId, and profile fields.
go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.