skip to Main Content

I tried to make an API with golang and postgres using gorm framework.I got error that said cannot use r.GetBooks (value of type func(context *fiber.Ctx) error) as func(*fiber.Ctx) value in argument to api.Get

Here’s my code:

import (
    "fmt"
    "log"
    "os"

    "net/http"

    "github.com/gofiber/fiber"
    "github.com/joho/godotenv"
    "gorm.io/gorm"
)


func (r *Repository) GetBooks(context *fiber.Ctx) error {
    bookModels := &[]models.Books{}

    err := r.DB.Find(bookModels).Error
    if err != nil {
        context.Status(http.StatusBadRequest).JSON(
            &fiber.Map{"message": "Failed to get the book"})
        return err
    }

    context.Status(http.StatusOK).JSON(
        &fiber.Map{
            "message": "Books fetched successfully",
            "data": bookModels,
        })

    return nil
}
func (r *Repository) SetupRoutes(app *fiber.App){
    
    api := app.Group("/api")

    api.Get("/books", r.GetBooks)
}

I already return nil at the end of the function and use error as a return for the function. But still didn’t work

2

Answers


  1. From your error
    cannot use r.GetBooks (value of type func(context *fiber.Ctx) error) as func(*fiber.Ctx) value in argument to api.Get

    Whats its expecting func(*fiber.Ctx)

    What you are giving func(*fiber.Ctx) error

    It’s expecting a function without a return type while your function is returning an error

    You need to modify your GetBooks function to not return anything

    func (r *Repository) GetBooks(context *fiber.Ctx) {
        bookModels := &[]models.Books{}
    
        err := r.DB.Find(bookModels).Error
        if err != nil {
            context.Status(http.StatusBadRequest).JSON(
                &fiber.Map{"message": "Failed to get the book"})
            return
        }
    
        context.Status(http.StatusOK).JSON(
            &fiber.Map{
                "message": "Books fetched successfully",
                "data": bookModels,
            })
    
        return
    }
    
    Login or Signup to reply.
  2. You are using an old version of the fiber framework from 2020.

    Import "github.com/gofiber/fiber/v2" (or the new v3 which is in beta) to get the handler definition of func(Ctx) error.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search