You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go Fiber依赖注入场景下Handler函数类型不匹配报错的解决

解决Go Fiber路由处理函数类型不匹配错误

错误信息

cannot use controller.UserController.FindAll (value of type func(_ controller.UserController, c *fiber.Ctx) error) as type func(*fiber.Ctx) error in argument to app.Get

出错代码

package route

package route

import (
    "go_fiber/controller"

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

func RouteInit(app *fiber.App) {
    app.Get("/users", controller.UserController.FindAll ) //此行报错
}

package controller

package controller

import (
    "go_fiber/model/web"
    "go_fiber/service"

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

type UserController interface{
    // Create(c *fiber.Ctx)
    // Update(c *fiber.Ctx)
    FindAll(c *fiber.Ctx) error
    // FindById(c *fiber.Ctx)
    // Delete(c *fiber.Ctx)
}

type UserControllerImpl struct {
    UserService service.UserService
}

func NewUserController(UserService service.UserService) UserController {
    return &UserControllerImpl{
        UserService: UserService,
    }
}

func (controller *UserControllerImpl) FindAll(c *fiber.Ctx) error {
    userResponse := controller.UserService.FindAll(c)

    webResponse := web.WebResponse{
        Code:    200,
        Status: "success",
        Data:    userResponse,
    }

    c.JSON(webResponse)

    return nil
}

错误原因

直接通过controller.UserController.FindAll调用接口方法时,得到的是未绑定具体实例的方法,其签名包含隐式的接收者参数_ controller.UserController,而Fiber的app.Get要求的处理函数签名是func(*fiber.Ctx) error,两者类型不匹配。

修复方案

先在程序入口创建UserController的具体实例,再将实例的FindAll方法传递给路由。

修复后的代码

package main

package main

import (
    "go_fiber/app"
    "go_fiber/controller"
    "go_fiber/repository"
    "go_fiber/route"
    "go_fiber/service"

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

func main(){

    db := app.NewDB()
    app.CreateDatabase(db)

    app := fiber.New()

    userRepository := repository.NewUserRepository()
    userService := service.NewUserService(userRepository, db)
    userController := controller.NewUserController(userService)

    route.RouteInit(app, userController)

    app.Listen(":3000")
}

package route

package route

import (
    "go_fiber/controller"

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

func RouteInit(app *fiber.App, userController controller.UserController) {
    app.Get("/users", userController.FindAll)
}

内容的提问来源于stack exchange,提问作者leo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 21:15:36