初步搭建02

This commit is contained in:
des
2026-01-13 13:02:27 +08:00
parent 0c68d57180
commit a289a90676
3 changed files with 45 additions and 19 deletions

View File

@@ -1,7 +1,6 @@
package main package main
import ( import (
"fmt"
"net/http" "net/http"
"github.com/labstack/echo" "github.com/labstack/echo"
@@ -10,15 +9,8 @@ import (
) )
func main() { func main() {
client := common.GetDataBaseClient() client, close := common.GetDataBaseClient()
defer close()
config, ero := client.DB()
if ero != nil {
fmt.Println("获取连接池失败")
panic(ero)
}
defer config.Close()
app := echo.New() app := echo.New()
app.GET("/", func(ctx echo.Context) error { app.GET("/", func(ctx echo.Context) error {
return ctx.String(http.StatusOK, "Hello, World!") return ctx.String(http.StatusOK, "Hello, World!")

View File

@@ -1,11 +1,18 @@
package common package common
import ( import (
"fmt"
"gorm.io/driver/postgres" "gorm.io/driver/postgres"
"gorm.io/gorm" "gorm.io/gorm"
) )
func GetDataBaseClient() *gorm.DB { // GetDataBaseClient 获取数据库链接
//
// 返回值
// - 一个 gorm.DB 的指针
// - 一个清理所有数据库相关数据的函数
func GetDataBaseClient() (*gorm.DB, func() error) {
dsn := "host=localhost " + dsn := "host=localhost " +
"user=gatekeeper " + "user=gatekeeper " +
"dbname=crimson " + "dbname=crimson " +
@@ -13,9 +20,21 @@ func GetDataBaseClient() *gorm.DB {
"port=5432 " + "port=5432 " +
"password=crimson " + "password=crimson " +
"connect_timeout=20 " "connect_timeout=20 "
client, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil { client, ero := gorm.Open(postgres.Open(dsn), &gorm.Config{})
panic("无法连接数据库") if ero != nil {
fmt.Println("数据库链接建立失败")
panic(ero)
} }
return client
poolCfg, ero := client.DB()
if ero != nil {
fmt.Println("获取数据库链接池失败")
panic(ero)
}
poolCfg.SetConnMaxIdleTime(3)
poolCfg.SetMaxOpenConns(10)
return client, poolCfg.Close
} }

View File

@@ -4,14 +4,29 @@ import (
"net/http" "net/http"
"github.com/labstack/echo" "github.com/labstack/echo"
"gorm.io/gorm"
) )
type Controller struct{} type Controller struct {
client *gorm.DB
group string
}
func (Controller) GetLogin(ctx echo.Context) error { func (*Controller) GetLogin(ctx echo.Context) error {
return ctx.String(http.StatusOK, "success") return ctx.String(http.StatusOK, "success")
} }
func New() *Controller { func (s *Controller) RegisterRoute(echo *echo.Echo) {
return &Controller{} echo.GET("/login", s.GetLogin)
}
// New 获取用户模块的控制器
//
// 参数
// - gorm.DB 该模块所使用的数据库链接
//
// 返回值
// - Controller 控制器的实例指针
func New(client *gorm.DB) *Controller {
return &Controller{client}
} }