go 查询用户信息接口

11 阅读1分钟

项目目录功能说明

image.png

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
    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"
)

// InitRouter 初始化路由引擎
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,
    }))

    // 2️⃣ 公开路由(无需认证)
    public := r.Group("/api/v1")
    {
       public.GET("/ping", handler.Ping)
       public.POST("/auth/login", admin.Login)
    }

    // 3️⃣ 受保护的路由(需要认证)
    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})
}