项目目录功能说明

1. 数据库连接
package main
import (
"hello/internal/dao"
"hello/internal/model"
"hello/internal/router"
)
func main() {
model.InitDB(model.DBConfig{
User: "xxx",
Password: "xxx",
Host: "xxx",
Port: 3306,
DBName: "my_test_db",
})
dao.NewUserDAO(model.DB)
r := router.InitRouter()
err := r.Run(":8080")
if err != nil {
return
}
}
2. 路由层调用
package router
import (
"hello/internal/handler"
"hello/internal/handler/admin"
"hello/internal/middleware"
"github.com/gin-gonic/gin"
)
func InitRouter() *gin.Engine {
r := gin.Default()
r.Use(middleware.Cors(middleware.CorsOptions{
AllowOrigins: []string{
"http://localhost:5173",
},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
AllowCredentials: true,
}))
public := r.Group("/api/v1")
{
public.GET("/ping", handler.Ping)
public.POST("/auth/login", admin.Login)
}
protected := r.Group("/api/v1")
{
protected.GET("/admin/profile", admin.GetProfile)
}
return r
}
3. Handler + Service + DAO
package admin
import (
"hello/internal/service/admin"
"hello/pkg/response"
"log"
"strconv"
"github.com/gin-gonic/gin"
)
type ProfileRequest struct {
UserId int64 `json:"user_id" binding:"required"`
}
func GetProfile(c *gin.Context) {
log.Println("get profile")
idStr := c.Query("id")
if idStr == "" {
response.Fail(c, "id is required")
return
}
userId, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
response.Fail(c, "invalid id")
return
}
profile, err := admin.ProfileService.GetProfile(userId)
if err != nil {
response.Fail(c, "failed to get profile")
return
}
response.Success(c, gin.H{"profile": profile})
}