go fiber:使用独立的routes文件组织controller

一,go代码:

controller/articleController.go

package controller

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

type ArticleController struct{}

func NewArticleController() *ArticleController {
	return &ArticleController{}
}

func (dc *ArticleController) GetArticle(c *fiber.Ctx) error {
	// 处理获取文章的逻辑
	return c.SendString("获取文章信息")
}

func (dc *ArticleController) CreateArticle(c *fiber.Ctx) error {
	// 处理创建文章的逻辑
	return c.SendString("创建文章")
}

controller/userController.go

package controller

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

type UserController struct{}

func NewUserController() *UserController {
	return &UserController{}
}

func (dc *UserController) GetUser(c *fiber.Ctx) error {
	// 处理获取用户的逻辑
	return c.SendString("获取用户信息")
}

func (dc *UserController) CreateUser(c *fiber.Ctx) error {
	// 处理创建用户的逻辑
	return c.SendString("创建用户")
}

routes/routes.go

package routes

import (
	"github.com/gofiber/fiber/v2"
	"industry/controller"
)

func SetupRoutes(app *fiber.App) {
	//文章模块
	articleController := controller.NewArticleController()
	article := app.Group("/article")
	article.Get("/info", articleController.GetArticle)
	article.Post("/", articleController.CreateArticle)

	//用户模块
	userController := controller.NewUserController()
	user := app.Group("/user")
	user.Get("/info", userController.GetUser)
	user.Post("/", userController.CreateUser)
}

main.go

package main

import (
	"github.com/gofiber/fiber/v2"
	"industry/routes"
)

func main() {

	app := fiber.New()

	// 设置路由
	routes.SetupRoutes(app)

	// 启动服务器
	err := app.Listen(":3000")
	if err != nil {
		return
	}

}

二,测试效果:

$ ./industry 

 ┌───────────────────────────────────────────────────┐ 
 │                   Fiber v2.52.5                   │ 
 │               http://127.0.0.1:3000               │ 
 │       (bound on host 0.0.0.0 and port 3000)       │ 
 │                                                   │ 
 │ Handlers ............. 6  Processes ........... 1 │ 
 │ Prefork ....... Disabled  PID .............. 2558 │ 
 └───────────────────────────────────────────────────┘ 

 

posted @ 2024-11-16 12:38  刘宏缔的架构森林  阅读(10)  评论(0编辑  收藏  举报