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?
Asked
Active
Viewed 334 times
1
-
1Are you intending do http calls to server spawned by go fiber? – Shahriar Ahmed Jul 04 '23 at 05:21
-
No, I want to create an HTTP request by using Fiber [Client](https://docs.gofiber.io/api/client/). Thanks for your reply. – javmah Jul 04 '23 at 05:29
2 Answers
1
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

PRATHEESH PC
- 1,461
- 1
- 3
- 15
-
Thank you so much for your code sample. Can you please kindly show me how can I add Headers to this request? Suppose I want to add
to the header how can I do that? Kindest Regards. – javmah Jul 05 '23 at 06:41 -
1You can use [Set method](https://github.com/gofiber/fiber/blob/master/client.go#L218) of `Agent` struct. I have updated the answer. – PRATHEESH PC Jul 05 '23 at 06:53
-
1See the [Header](https://github.com/gofiber/fiber/blob/master/client.go#L213) section, as it have more methods to add the headers with the request. – PRATHEESH PC Jul 05 '23 at 06:58
1
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)
}
}

javmah
- 99
- 2
- 6