How to make a GET request in Go Fiber to an API endpoint?

1.9k Views Asked by At

How to make a GET request in GO Fiber. I saw Fiber client but there is no working example code there. Could anyone kindly show me how to do that? suppose there is a API endpoint https://jsonplaceholder.typicode.com/posts How can I get the data from that endpoint using the Fiber client?

2

There are 2 best solutions below

4
On

The client feature has released with v2.6.0. And see the implemention commit at here

Also see client.go

Here is the sample code

package main

import (
    "encoding/json"
    "fmt"

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

type user struct {
    UserID int    `json:"userId"`
    ID     int    `json:"id"`
    Title  string `json:"title"`
    Body   string `json:"body"`
}

func main() {
    request := fiber.Get("https://jsonplaceholder.typicode.com/posts")
    request.Debug()

    // to set headers
    request.Set("header-token", "value")

    _, data, err := request.Bytes()
    if err != nil {
        panic(err)
    }

    var users []user
    jsonErr := json.Unmarshal(data, &users)
    if jsonErr != nil {
        panic(err)
    }

    for _, data := range users {
        fmt.Println("UserID : ", data.UserID)
        fmt.Println("Title : ", data.Title)
    }

}

You can use the other http methods as

fiber.Post()
fiber.Patch()
fiber.Put()
fiber.Delete()

Hope this helps

1
On

Thanks to Renan Bastos(@renanbastos93). I got another working code example.

package main
import (
    "encoding/json"
    "github.com/gofiber/fiber/v2"
)
type Posts struct {
    UserID int    `json:"userId"`
    ID     int    `json:"id"`
    Title  string `json:"title"`
    Body   string `json:"body"`
}
type AllPosts []Posts

func getPosts(c *fiber.Ctx) (err error) {
    agent := fiber.AcquireAgent()
    agent.Request().Header.SetMethod("GET")
    agent.Request().SetRequestURI("https://jsonplaceholder.typicode.com/posts")
    err = agent.Parse()
    if err != nil {
        return c.SendStatus(fiber.StatusInternalServerError)
    }
    var allPosts AllPosts
    statusCode, body, errs := agent.Bytes()
    if len(errs) > 0 {
        return c.Status(statusCode).JSON(errs)
    }
    err = json.Unmarshal(body, &allPosts)
    if err != nil {
        return c.SendStatus(fiber.StatusInternalServerError)
    }
    return c.JSON(allPosts)
}

func main() {
    f := fiber.New()
    f.Get("/", getPosts)
    err := f.Listen(":9000")
    if err != nil {
        panic(err)
    }
}