Home > Blockchain >  How to set Routes Group in Go Fiber from Separated file?
How to set Routes Group in Go Fiber from Separated file?

Time:02-11

I want to make seperate files for each sub main routes. I am using go 1.17

main.go

package main

import (
    "rolling_glory_go/routes"

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

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

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

    routes.R_login(app.Group("/login"))
    routes.R_users(app.Group("/users"))

    app.Listen(":3000")
}

I want to import routes from r_login.go and r_users.go so i could manage many routes from different files and not put many routes from single file in main.go. I got an error like this.

.\main.go:17:26: cannot use app.Group("/login") (type fiber.Router) as type *fiber.Group in argument to routes.R_login: need type assertion
.\main.go:18:26: cannot use app.Group("/users") (type fiber.Router) as type *fiber.Group in argument to routes.R_users: need type assertion

My Structure Folder

enter image description here

r_login.go

package routes

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

func R_login(router *fiber.Group) {
    router.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("respond with a resource")
    })
}

r_users.go

package routes

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

func R_users(router *fiber.Group) {
    router.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("respond with a resource")
    })
}

How to fix this ?

CodePudding user response:

As you have app.Group("/login") which of type fiber.Router , just modify R_login to have it accept this type.

package routes

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

func R_login(router fiber.Router) {
    router.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("respond with a resource")
    })
}
  • Related