### Install Dependencies and Start Server Source: https://www.youlai.tech/docs/server/django/quick-start.html Commands to set up the virtual environment, install dependencies, and start the Django development server. ```bash python -m venv venv source venv/bin/activate # Linux/macOS # venv\Scripts\activate # Windows pip install -r requirements.txt python manage.py runserver 0.0.0.0:8000 ``` -------------------------------- ### Install project dependencies Source: https://www.youlai.tech/docs/web/naiveui/faq/electron.html Navigate to the cloned directory and install the required dependencies. ```bash cd electron-app pnpm i ``` -------------------------------- ### Install Zap Source: https://www.youlai.tech/docs/server/gin/practice/logger.html Installs the Zap logging library for Go. ```bash go get go.uber.org/zap ``` -------------------------------- ### Install Wire CLI and Library Source: https://www.youlai.tech/docs/server/gin/practice/wire.html Installs the Wire command-line tool and the Wire library for Go modules. ```bash go install github.com/google/wire/cmd/wire@latest go get github.com/google/wire ``` -------------------------------- ### Setup Store 写法示例 (src/stores/user.ts) Source: https://www.youlai.tech/docs/web/development/code-standard.html 使用 Pinia 的 Setup Store 语法定义用户 Store,包含 State、Getter 和 Action。State 使用 ref 定义,Getter 使用 computed,Action 为异步或普通函数。示例中展示了登录、获取用户信息和登出等操作。 ```typescript // src/stores/user.ts import { defineStore } from "pinia"; import AuthAPI from "@/api/auth"; import type { UserInfo } from "@/api/system/user"; export const useUserStore = defineStore("user", () => { // State const userInfo = ref(null); const token = ref(""); // Getters const isLoggedIn = computed(() => !!token.value); const userId = computed(() => userInfo.value?.id); const roles = computed(() => userInfo.value?.roles ?? []); // Actions async function login(username: string, password: string) { const { accessToken } = await AuthAPI.login({ username, password }); token.value = accessToken; } async function fetchUserInfo() { userInfo.value = await AuthAPI.getUserInfo(); } function logout() { token.value = ""; userInfo.value = null; } return { // State userInfo, token, // Getters isLoggedIn, userId, roles, // Actions login, fetchUserInfo, logout, }; }); ``` -------------------------------- ### Store Hook 在非 setup 上下文使用示例 Source: https://www.youlai.tech/docs/web/development/code-standard.html 定义 useUserStoreHook 函数,在非 setup 上下文(如路由守卫)中通过传入 store 实例来使用 useUserStore。示例展示了在路由守卫中检查登录状态并重定向到登录页。 ```typescript // 定义 Hook import { store } from "@/stores"; export function useUserStoreHook() { return useUserStore(store); } // 在非 setup 上下文使用(如路由守卫) import { useUserStoreHook } from "@/stores"; router.beforeEach((to, from, next) => { const userStore = useUserStoreHook(); if (!userStore.isLoggedIn) { next("/login"); } }); ``` -------------------------------- ### Start development server Source: https://www.youlai.tech/docs/element/quick-start.html Starts the development server. After successful startup, access the local address printed in the terminal, typically http://localhost:3000. ```bash pnpm run dev ``` -------------------------------- ### Exception log output example Source: https://www.youlai.tech/docs/server/spring-boot/modules-logging.html Example output showing an error log with a full stack trace. ```text 2024-01-15 10:30:45.123 -ERROR ---[nio-8000-exec-1] c.y.b.o.service.OrderService : 订单创建失败: orderId=12345 java.lang.NullPointerException: 商品不存在 at com.youlai.boot.order.service.OrderService.createOrder(OrderService.java:50) ... ``` -------------------------------- ### Create a Pinia store with setup syntax (store/modules/user.ts) Source: https://www.youlai.tech/docs/element/core/state-management.html Defines a user store using the setup syntax with state (token, userInfo, roles), a computed username, and actions for login, getUserInfo, and logout. Uses ref, computed, and external API functions. ```typescript // store/modules/user.ts import { defineStore } from 'pinia' export const useUserStore = defineStore('user', () => { // 状态 const token = ref('') const userInfo = ref() const roles = ref([]) // 计算属性 const username = computed(() => userInfo.value?.username || '') // 方法 async function login(data: LoginForm) { const res = await AuthAPI.login(data) token.value = res.data.token setToken(res.data.token) } async function getUserInfo() { const res = await UserAPI.getUserInfo() userInfo.value = res.data roles.value = res.data.roles } function logout() { token.value = '' removeToken() router.push('/login') } return { token, userInfo, roles, username, login, getUserInfo, logout } }) ``` -------------------------------- ### 安装 Swagger 依赖 Source: https://www.youlai.tech/docs/server/gin/practice/swagger.html 使用 go get 安装 gin-swagger、files 包,以及通过 go install 安装 swag 命令行工具。这是集成 Swagger 的前提步骤。 ```bash go get github.com/swaggo/gin-swagger go get github.com/swaggo/files go install github.com/swaggo/swag/cmd/swag@latest ``` -------------------------------- ### 设置环境变量并启动应用 Source: https://www.youlai.tech/docs/server/gin/dev-config.html 通过设置 APP_ENV 环境变量来选择加载的配置文件,然后使用 go run main.go 启动应用。 ```bash # 开发环境 export APP_ENV=dev # 生产环境 export APP_ENV=prod # 启动应用 go run main.go ``` -------------------------------- ### 在 main.go 中调用数据库初始化 Source: https://www.youlai.tech/docs/server/gin/practice/database.html 在服务启动时调用 database.Init,确保数据库连接可用后再注册路由。 ```go // 数据库初始化应放在路由注册之前。 // 如果数据库不可用,服务不应该继续启动。 if err := database.Init(config.Cfg.Database); err != nil { log.Fatalf("数据库初始化失败: %v", err) } ``` -------------------------------- ### Basic TextScroll usage Source: https://www.youlai.tech/docs/element/components/text-scroll.html Basic usage of the TextScroll component. The `text` prop is required and accepts a string. The example uses a Vue 3 ` ``` -------------------------------- ### 定义 GET 请求 Source: https://www.youlai.tech/docs/naiveui/guide/request-service 使用 get 方法发起 GET 请求,并指定返回数据类型。 ```ts import { get } from "@/utils"; interface IGetData { id: number; name: string; } // 传递的类型对应接口返回的 data 类型 export const fetachGet: () => get(`/get`, { id: 1 }), ``` -------------------------------- ### 生成文档并运行服务 Source: https://www.youlai.tech/docs/server/gin/practice/swagger.html 使用 swag init 从 main.go 生成 api 目录下的文档,然后运行 Go 服务。 ```bash swag init -g main.go -o api go run main.go ``` -------------------------------- ### Install dependencies Source: https://www.youlai.tech/docs/element/quick-start.html Enables Corepack and installs dependencies using pnpm. ```bash corepack enable pnpm install ``` -------------------------------- ### Initialize Database Source: https://www.youlai.tech/docs/server/django/quick-start.html Execute the SQL script to initialize the database. ```bash mysql -u root -p < sql/mysql/youlai_admin_django.sql ``` -------------------------------- ### Generated Entity Example Source: https://www.youlai.tech/docs/server/nestjs/dev-codegen.html An example of a TypeORM entity class generated by the tool. ```typescript @Entity("sys_user") export class User { @PrimaryGeneratedColumn({ type: "bigint" }) id: number; @Column({ length: 50 }) username: string; @Column() deptId: number; } ``` -------------------------------- ### Log output example Source: https://www.youlai.tech/docs/server/spring-boot/modules-logging.html An example of a formatted log line based on the defined pattern. ```text 2024-01-15 10:30:45.123 - INFO ---[nio-8000-exec-1] c.y.b.a.controller.AuthController : 用户登录成功: admin ``` -------------------------------- ### main.go 使用配置 Source: https://www.youlai.tech/docs/server/gin/practice/config.html 在 `main.go` 中,先调用 `config.Load()` 加载配置,如果失败则直接终止启动。然后创建 Gin 实例,设置一个临时的 `/ping` 接口验证服务,并从配置中读取端口启动 HTTP 服务。 ```go package main import ( "fmt" "log" "github.com/gin-gonic/gin" "youlai-gin/internal/common/config" ) func main() { // 1. 应用启动第一步先加载配置。 // 如果配置文件不存在或格式错误,直接终止启动。 if err := config.Load(); err != nil { log.Fatalf("配置加载失败: %v", err) } // 2. 创建 Gin 实例。 // 这里先用 gin.New(),后续章节再逐步挂载日志、异常处理等中间件。 r := gin.New() // 3. 临时保留一个 ping 接口,用来验证服务是否启动成功。 r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{"msg": "pong"}) }) // 4. 从配置中读取端口,拼成 Gin 监听地址,例如 :8000。 addr := fmt.Sprintf(":%d", config.Cfg.Server.Port) // 5. 启动 HTTP 服务。 r.Run(addr) } ``` -------------------------------- ### 数据库配置 - .env Source: https://www.youlai.tech/docs/server/thinkphp/quick-start.html 复制 .env.example 为 .env 后,根据本地环境修改数据库连接信息。 ```dotenv DB_HOST=localhost DB_PORT=3306 DB_NAME=youlai_admin DB_USER=root DB_PASS=your_password ``` -------------------------------- ### Permission Identifier Examples Source: https://www.youlai.tech/docs/server/spring-boot/dev-standards.html Concrete examples of permission identifiers for user, role, and notice management modules. ```java // 用户管理 sys:user:list // 列表 sys:user:create // 新增 sys:user:update // 修改 sys:user:delete // 删除 sys:user:import // 导入 sys:user:export // 导出 sys:user:reset-password // 重置密码 // 角色管理 sys:role:create sys:role:update sys:role:delete sys:role:assign // 分配权限 // 公告管理 sys:notice:list sys:notice:create sys:notice:update sys:notice:delete sys:notice:publish // 发布 sys:notice:revoke // 撤销 ``` -------------------------------- ### 测试目录结构 Source: https://www.youlai.tech/docs/web/development/testing.html 展示测试文件的目录组织,包括 utils、store、composables、components 子目录和 setup.ts 配置文件。 ```text tests/ ├── unit/ │ ├── utils/ # 工具函数测试 │ ├── store/ # Store 模块测试 │ ├── composables/ # 组合式函数测试 │ └── components/ # 组件测试 └── setup.ts # 测试环境配置 ``` -------------------------------- ### Structured JSON Log Example Source: https://www.youlai.tech/docs/server/spring-boot/modules-logging.html Example of a structured log entry containing a traceId for Kibana aggregation. ```json { "traceId": "a1b2c3d4e5f6", "service": "system-service", "userId": 1, "method": "UserController.getPage", "duration": 156, "status": "SUCCESS" } ``` -------------------------------- ### 启动服务 Source: https://www.youlai.tech/docs/server/gin/practice/deploy.html 使用 APP_ENV=prod 环境变量启动编译后的二进制文件。 ```bash APP_ENV=prod ./bin/youlai-gin ``` -------------------------------- ### GET 和 POST 请求示例 Source: https://www.youlai.tech/docs/app/core/request.html 使用统一的 request 封装发起 GET 和 POST 请求。GET 请求获取用户信息,POST 请求登录。 ```typescript import request from "@/utils/request" // GET const data = await request({ url: "/api/v1/users/me", method: "GET" }) // POST const result = await request({ url: "/api/v1/auth/login", method: "POST", data }) ``` -------------------------------- ### 开发环境 .env.development 配置 Source: https://www.youlai.tech/docs/element/development/configuration.html 开发环境的环境变量配置,包括端口、项目名称、代理前缀、接口地址和 Mock 开关。 ```bash # 应用端口 VITE_APP_PORT=3000 # 项目名称 VITE_APP_TITLE=vue3-element-admin # 代理前缀 VITE_APP_BASE_API=/dev-api # 接口地址(线上接口) VITE_APP_API_URL=https://api.youlai.tech # VITE_APP_API_URL=http://localhost:8000 # 本地接口 # 启用 Mock 服务 VITE_MOCK_DEV_SERVER=false ``` -------------------------------- ### Install dependencies via Composer Source: https://www.youlai.tech/docs/server/thinkphp/deploy.html Run this command to install project dependencies for production without development packages. ```bash composer install --no-dev --optimize-autoloader ``` -------------------------------- ### 初始化 GORM 全局连接 Source: https://www.youlai.tech/docs/server/gin/practice/database.html 在 internal/common/database/database.go 中实现 Init 函数,配置连接池并初始化全局 DB 变量。 ```go package database import ( "time" "gorm.io/driver/mysql" "gorm.io/gorm" ) // DB 保存全局数据库连接。 // 简化阶段先全局使用,后面 Repository 会通过它访问数据库。 var DB *gorm.DB func Init(cfg Config) error { // 使用配置生成 DSN,并创建 GORM 连接。 db, err := gorm.Open(mysql.Open(cfg.DSN()), &gorm.Config{}) if err != nil { return err } // GORM 底层仍然使用 database/sql,这里取出底层连接池做参数设置。 sqlDB, err := db.DB() if err != nil { return err } // 最大空闲连接数:控制空闲连接池大小。 sqlDB.SetMaxIdleConns(cfg.MaxIdleConns) // 最大打开连接数:控制应用最多占用多少数据库连接。 sqlDB.SetMaxOpenConns(cfg.MaxOpenConns) // 单个连接最大复用时间,避免长连接一直不释放。 sqlDB.SetConnMaxLifetime(time.Duration(cfg.ConnMaxLifetime) * time.Second) // 初始化成功后赋值给全局 DB,供 Repository 使用。 DB = db return nil } ``` -------------------------------- ### Form Integration Example Source: https://www.youlai.tech/docs/web/components/upload.html Example of using SingleImageUpload, MultiImageUpload, and FileUpload components within an Element Plus form. ```vue ``` -------------------------------- ### Java Service Interface Naming Example Source: https://www.youlai.tech/docs/server/spring-boot/dev-standards.html A comprehensive example of a service interface following the defined naming conventions. ```java public interface UserService { // 查询方法 User getUserById(Long id); // 单个查询 UserForm getUserFormData(Long id); // 获取表单数据 IPage getUserPage(UserQuery q); // 分页查询 List listUsers(); // 列表查询 List> listUserOptions(); // 下拉选项 boolean existsByUsername(String username); // 存在性判断 // 写操作方法 boolean saveUser(UserForm form); // 新增 boolean updateUser(Long id, UserForm form); // 修改 boolean deleteUsers(String ids); // 删除(批量) boolean resetUserPassword(Long id, String pwd); // 特殊操作 } ``` -------------------------------- ### 添加 spring-boot-starter-web 依赖(包含日志) Source: https://www.youlai.tech/docs/server/spring-boot/modules-logging.html Spring Boot 自动引入 spring-boot-starter-logging,无需额外配置。 ```xml org.springframework.boot spring-boot-starter-web ``` -------------------------------- ### Install dependencies for login authentication Source: https://www.youlai.tech/docs/server/gin/practice/auth.html Install the bcrypt, JWT, and base64Captcha packages required for login authentication and JWT issuance. ```bash go get golang.org/x/crypto/bcrypt go get github.com/golang-jwt/jwt/v5 go get github.com/mojocn/base64Captcha ``` -------------------------------- ### 注册 Swagger 路由 Source: https://www.youlai.tech/docs/server/gin/practice/swagger.html 在 main.go 中引入生成的 api 包、Swagger 文件包和 Handler。空导入会触发 api 包的 init() 注册 Swagger 元信息。 ```go import ( // 这个空导入很关键: _ "youlai-gin/api" swaggerFiles "github.com/swaggo/files" ginSwagger "github.com/swaggo/gin-swagger" ) ``` -------------------------------- ### SQL Sharding Query Example Source: https://www.youlai.tech/docs/server/spring-boot/modules-scheduler.html Example SQL query using modulo operator to filter data based on sharding parameters. ```sql -- 根据分片参数查询数据 SELECT * FROM orders WHERE MOD(id, #{shardTotal}) = #{shardIndex} ``` -------------------------------- ### initialize() Source: https://www.youlai.tech/docs/element/composables/use-dict-sync.html 初始化 SSE 连接并订阅字典事件。应在应用启动时调用一次。 ```APIDOC ## initialize() ### Description 初始化 SSE 连接并订阅字典事件。应在应用启动时调用一次。 ### Method Function ### Signature `initialize(): void` ### Parameters 无 ### Returns - **void** ### Example ```typescript const dictSync = useDictSync(); dictSync.initialize(); ``` ``` -------------------------------- ### Role Permission Assignment Example Source: https://www.youlai.tech/docs/app/components/tree.html A complete example demonstrating role permission assignment using checkable, checked-keys, and the content slot. ```vue ``` -------------------------------- ### Start Docker Compose stack Source: https://www.youlai.tech/docs/server/axum/deploy.html Starts the Docker Compose stack defined in docker/docker-compose.yml with project name youlai-axum in detached mode. ```bash docker compose -f docker/docker-compose.yml -p youlai-axum up -d ``` -------------------------------- ### 本地构建 Go 二进制 Source: https://www.youlai.tech/docs/server/gin/practice/deploy.html 使用 go build 编译项目,输出到 bin/youlai-gin。 ```bash go build -o bin/youlai-gin main.go ``` -------------------------------- ### 注册 hello 模块路由 (router.go) Source: https://www.youlai.tech/docs/server/gin/practice/hello.html 定义 RegisterRoutes 函数,注册 hello 模块自己的路由。每个模块维护自己的路由,便于项目扩展。 ```go package hello import "github.com/gin-gonic/gin" // RegisterRoutes 只注册 hello 模块自己的路由。 // 每个模块维护自己的路由,项目大了之后更容易查找。 func RegisterRoutes(r *gin.RouterGroup) { r.GET("/hello", Hello) } ``` -------------------------------- ### 配置 SSE 环境变量 Source: https://www.youlai.tech/docs/element/composables/use-dict-sync.html 在 .env 文件中配置 SSE 端点,若未配置则自动跳过初始化。 ```bash VITE_APP_SSE_ENDPOINT=http://localhost:8080/api/v1/sse/connect ``` -------------------------------- ### 建立 SSE 连接 (GET /api/v1/sse/connect) Source: https://www.youlai.tech/docs/server/nestjs/modules-realtime.html 使用 HTTP GET 请求建立 SSE 连接,需要携带 Bearer token 认证,并设置 Accept 头为 text/event-stream。 ```http GET /api/v1/sse/connect Authorization: Bearer Accept: text/event-stream ``` -------------------------------- ### systemd 服务文件 Source: https://www.youlai.tech/docs/server/gin/deploy.html 创建 systemd 服务文件 /etc/systemd/system/youlai-gin.service,用于管理 youlai-gin 服务。 ```ini [Unit] Description=Youlai Gin Service After=network.target [Service] Type=simple User=app WorkingDirectory=/opt/youlai-gin Environment=APP_ENV=prod ExecStart=/opt/youlai-gin/youlai-gin Restart=always RestartSec=5 [Install] WantedBy=multi-user.target ``` -------------------------------- ### Package the application Source: https://www.youlai.tech/docs/web/naiveui/faq/electron.html Run the build command to package the application using electron-builder, showing the expected output logs. ```bash PS E:\Code\electron-app> pnpm build > electron-app@1.5.0 build E:\Code\electron-app > electron-builder • electron-builder version=26.0.12 os=10.0.26100 • loaded configuration file=package.json ("build" field) • description is missed in the package.json appPackageFile=E:\Code\electron-app\package.json • author is missed in the package.json appPackageFile=E:\Code\electron-app\package.json • writing effective config file=dist_electron\builder-effective-config.yaml • executing @electron/rebuild electronVersion=37.2.4 arch=x64 buildFromSource=false appDir=./ • installing native dependencies arch=x64 • completed installing native dependencies • packaging platform=win32 arch=x64 electron=37.2.4 appOutDir=dist_electron\win-unpacked • updating asar integrity executable resource executablePath=dist_electron\win-unpacked\待办事项清单.exe • signing with signtool.exe path=dist_electron\win-unpacked\待办事项清单.exe • building target=nsis file=dist_electron\待办事项清单 Setup 1.5.0.exe archs=x64 oneClick=false perMachine=false • signing with signtool.exe path=dist_electron\win-unpacked\resources\elevate.exe • signing with signtool.exe path=dist_electron\__uninstaller-nsis-electron-app.exe • signing with signtool.exe path=dist_electron\待办事项清单 Setup 1.5.0.exe • building block map blockMapFile=dist_electron\待办事项清单 Setup 1.5.0.exe.blockmap PS E:\Code\electron-app> ``` -------------------------------- ### Use store outside of setup (Pinia outside) Source: https://www.youlai.tech/docs/element/core/state-management.html Demonstrates using a Pinia store outside of a component setup context, such as in a utility function, by calling useUserStore() and accessing its state. ```typescript import { useUserStore } from '@/store/modules/user' // 需要在 setup 之外使用 export function checkAuth() { const userStore = useUserStore() return userStore.token !== '' } ``` -------------------------------- ### 浏览器访问接口 Source: https://www.youlai.tech/docs/server/gin/practice/hello.html GET 接口可以直接在浏览器地址栏访问,适合快速验证接口是否能访问。 ```text http://localhost:8000/api/v1/hello ```