gorig-cli 1.0.7 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/commands/init.js CHANGED
@@ -2,7 +2,7 @@ import fs from 'fs-extra';
2
2
  import path from 'path';
3
3
  import chalk from 'chalk';
4
4
  import ejs from 'ejs';
5
- import { exec } from 'child_process';
5
+ import { exec, spawn } from 'child_process';
6
6
  import { fileURLToPath } from 'url';
7
7
  import readline from 'readline';
8
8
 
@@ -15,7 +15,7 @@ const checkGoEnvironment = () => {
15
15
  return new Promise((resolve, reject) => {
16
16
  exec('go version', (error, stdout, stderr) => {
17
17
  if (error) {
18
- reject(new Error('未检测到 Go 环境,请先安装 Go 语言环境,访问 https://golang.org/dl/ 进行安装。'));
18
+ reject(new Error('Go environment not detected, please install Go language environment first, visit https://golang.org/dl/ for installation.'));
19
19
  } else {
20
20
  resolve(stdout);
21
21
  }
@@ -28,7 +28,7 @@ const addGorigDependency = (projectDir) => {
28
28
  return new Promise((resolve, reject) => {
29
29
  exec('go get github.com/jom-io/gorig@latest', { cwd: projectDir }, (error, stdout, stderr) => {
30
30
  if (error) {
31
- reject(new Error(`无法添加 gorig 依赖: ${stderr}`));
31
+ reject(new Error(`Failed to add gorig dependency: ${stderr}`));
32
32
  } else {
33
33
  resolve(stdout);
34
34
  }
@@ -41,7 +41,7 @@ const runGoModTidy = (projectDir) => {
41
41
  return new Promise((resolve, reject) => {
42
42
  exec('go mod tidy', { cwd: projectDir }, (error, stdout, stderr) => {
43
43
  if (error) {
44
- reject(new Error(`运行 go mod tidy 失败: ${stderr}`));
44
+ reject(new Error(`Failed to run go mod tidy: ${stderr}`));
45
45
  } else {
46
46
  resolve(stdout);
47
47
  }
@@ -57,7 +57,7 @@ const askOverwriteConfirmation = (projectDir) => {
57
57
  output: process.stdout
58
58
  });
59
59
  rl.question(
60
- chalk.yellow(`目录 ${chalk.bold(projectDir)} 已经存在,是否覆盖?(y/N): `),
60
+ chalk.yellow(`Directory ${chalk.bold(projectDir)} already exists, do you want to overwrite? (y/N): `),
61
61
  (answer) => {
62
62
  rl.close();
63
63
  if (answer.toLowerCase() === 'y') {
@@ -70,10 +70,36 @@ const askOverwriteConfirmation = (projectDir) => {
70
70
  });
71
71
  };
72
72
 
73
+ // 询问用户是否启动项目,超时5秒
74
+ const askStartConfirmation = () => {
75
+ return new Promise((resolve) => {
76
+ const rl = readline.createInterface({
77
+ input: process.stdin,
78
+ output: process.stdout
79
+ });
80
+
81
+ // 设置5秒超时
82
+ const timeout = setTimeout(() => {
83
+ rl.close();
84
+ resolve(false);
85
+ }, 5000);
86
+
87
+ rl.question('\nDo you want to start the project now? (y/N): ', (answer) => {
88
+ clearTimeout(timeout);
89
+ rl.close();
90
+ if (answer.toLowerCase() === 'y') {
91
+ resolve(true);
92
+ } else {
93
+ resolve(false);
94
+ }
95
+ });
96
+ });
97
+ };
98
+
73
99
  // 初始化项目的主函数
74
100
  const initModule = async (args) => {
75
101
  if (args.length < 1) {
76
- console.error(chalk.yellow('请使用正确的命令格式: npx <你的包名> init <项目名>'));
102
+ console.error(chalk.yellow('Please use the correct command format: npx <your package name> init <project name>'));
77
103
  process.exit(1);
78
104
  }
79
105
 
@@ -85,22 +111,22 @@ const initModule = async (args) => {
85
111
  // 定义需要创建的子目录
86
112
  const subDirs = ['_bin', '_cmd', 'domain', 'global', 'cron'];
87
113
 
88
- console.log(chalk.blue(`\n开始初始化项目: ${chalk.bold(projectName)}`));
114
+ console.log(chalk.blue(`\nStarting project initialization: ${chalk.bold(projectName)}`));
89
115
 
90
116
  try {
91
117
  // 检查本地是否存在 Go 环境
92
118
  await checkGoEnvironment();
93
- console.log(chalk.green('检测到 Go 环境,继续进行项目初始化...'));
119
+ console.log(chalk.green('Go environment detected, continuing project initialization...'));
94
120
 
95
121
  // 检查项目目录是否已存在
96
122
  if (await fs.pathExists(projectDir)) {
97
123
  const shouldOverwrite = await askOverwriteConfirmation(projectDir);
98
124
  if (!shouldOverwrite) {
99
- console.log(chalk.red('项目初始化已取消。'));
125
+ console.log(chalk.red('Project initialization has been canceled.'));
100
126
  process.exit(0);
101
127
  } else {
102
128
  await fs.remove(projectDir); // 删除已有的目录
103
- console.log(chalk.yellow(`已删除现有目录: ${chalk.bold(projectDir)}`));
129
+ console.log(chalk.yellow(`Deleted existing directory: ${chalk.bold(projectDir)}`));
104
130
  }
105
131
  }
106
132
 
@@ -118,17 +144,17 @@ const initModule = async (args) => {
118
144
  const goModPath = path.join(projectDir, 'go.mod');
119
145
  const goModContent = `module ${projectName}\n\ngo 1.20\n`;
120
146
  await fs.writeFile(goModPath, goModContent);
121
- console.log(chalk.green(`成功创建 ${chalk.bold('go.mod')} 文件`));
147
+ console.log(chalk.green(`Successfully created ${chalk.bold('go.mod')} file`));
122
148
 
123
149
  // 添加 gorig 依赖
124
- console.log(chalk.blue('添加 gorig 依赖中,请稍候...'));
150
+ console.log(chalk.blue('Adding gorig dependency, please wait...'));
125
151
  await addGorigDependency(projectDir);
126
- console.log(chalk.green(`成功添加 github.com/jom-io/gorig 最新版本的依赖`));
152
+ console.log(chalk.green(`Successfully added the latest version of github.com/jom-io/gorig dependency`));
127
153
 
128
154
  // 创建 _bin 目录下的配置文件
129
155
  const binDir = path.join(projectDir, '_bin');
130
156
  const configTemplatePath = path.join(__dirname, '../templates/config.yaml.ejs');
131
-
157
+
132
158
  const environments = ['dev', 'local', 'prod'];
133
159
  for (const env of environments) {
134
160
  const configFilePath = path.join(binDir, `${env}.yaml`);
@@ -138,7 +164,7 @@ const initModule = async (args) => {
138
164
  mode: env,
139
165
  });
140
166
  await fs.writeFile(configFilePath, configContent);
141
- console.log(chalk.green(`成功创建 ${chalk.bold(`${env}.yaml`)} 文件`));
167
+ console.log(chalk.green(`Successfully created ${chalk.bold(`${env}.yaml`)} file`));
142
168
  }
143
169
 
144
170
  // 创建 domain/init.go 文件
@@ -147,7 +173,7 @@ const initModule = async (args) => {
147
173
  const initGoTemplatePath = path.join(__dirname, '../templates/init.go.ejs');
148
174
  const initGoContent = await ejs.renderFile(initGoTemplatePath, { projectNameUpper });
149
175
  await fs.writeFile(initGoPath, initGoContent);
150
- console.log(chalk.green(`成功创建 ${chalk.bold('init.go')} 文件`));
176
+ console.log(chalk.green(`Successfully created ${chalk.bold('init.go')} file`));
151
177
 
152
178
  // 创建 _cmd/main.go 文件
153
179
  const cmdDir = path.join(projectDir, '_cmd');
@@ -155,7 +181,7 @@ const initModule = async (args) => {
155
181
  const mainGoTemplatePath = path.join(__dirname, '../templates/main.go.ejs');
156
182
  const mainGoContent = await ejs.renderFile(mainGoTemplatePath, { projectName });
157
183
  await fs.writeFile(mainGoPath, mainGoContent);
158
- console.log(chalk.green(`成功创建 ${chalk.bold('main.go')} 文件`));
184
+ console.log(chalk.green(`Successfully created ${chalk.bold('main.go')} file`));
159
185
 
160
186
  // 创建 global/config.go 文件
161
187
  const globalDir = path.join(projectDir, 'global');
@@ -163,7 +189,7 @@ const initModule = async (args) => {
163
189
  const configGoTemplatePath = path.join(__dirname, '../templates/config.go.ejs');
164
190
  const configGoContent = await ejs.renderFile(configGoTemplatePath, { projectNameUpper });
165
191
  await fs.writeFile(configGoPath, configGoContent);
166
- console.log(chalk.green(`成功创建 ${chalk.bold('config.go')} 文件`));
192
+ console.log(chalk.green(`Successfully created ${chalk.bold('config.go')} file`));
167
193
 
168
194
  // 创建 cron/cron.go 文件
169
195
  const cronDir = path.join(projectDir, 'cron');
@@ -171,23 +197,79 @@ const initModule = async (args) => {
171
197
  const cronGoTemplatePath = path.join(__dirname, '../templates/cron.go.ejs');
172
198
  const cronGoContent = await ejs.renderFile(cronGoTemplatePath, {});
173
199
  await fs.writeFile(cronGoPath, cronGoContent);
174
- console.log(chalk.green(`成功创建 ${chalk.bold('cron.go')} 文件`));
200
+ console.log(chalk.green(`Successfully created ${chalk.bold('cron.go')} file`));
175
201
 
176
202
  // 运行 go mod tidy
177
- console.log(chalk.blue('整理 Go 模块依赖中 (go mod tidy),请稍候...'));
203
+ console.log(chalk.blue('Organizing Go module dependencies (go mod tidy), please wait...'));
178
204
  await runGoModTidy(projectDir);
179
- console.log(chalk.green('成功整理 Go 模块依赖'));
205
+ console.log(chalk.green('Successfully organized Go module dependencies'));
180
206
 
181
- // 提示用户如何运行项目
182
- console.log(chalk.blue(`\n项目 ${chalk.bold(projectName)} 已成功创建在 ${chalk.bold(projectDir)} 目录下`));
183
- console.log(chalk.yellow('\n运行项目的方法:'));
184
- console.log(chalk.green(`1. 进入项目目录: cd ${projectName}`));
185
- console.log(chalk.green(`2. 使用 Go 命令运行项目:`));
207
+ // 提示用户项目创建成功
208
+ console.log(chalk.blue(`\nProject ${chalk.bold(projectName)} has been successfully created in ${chalk.bold(projectDir)} directory`));
209
+ console.log(chalk.yellow('\nHow to run the project:'));
210
+ console.log(chalk.green(`1. Enter the project directory: cd ${projectName}`));
211
+ console.log(chalk.green(`2. Use Go command to run the project:`));
186
212
  console.log(chalk.cyan(` go run _cmd/main.go`));
187
- console.log(chalk.green(`\n或者直接编译并运行:`));
213
+ console.log(chalk.green(`\nOr compile and run directly:`));
188
214
  console.log(chalk.cyan(` go build -o ${projectName} _cmd/main.go && ./${projectName}`));
215
+
216
+ // 询问用户是否启动项目
217
+ const shouldStart = await askStartConfirmation();
218
+ if (shouldStart) {
219
+ // 启动项目
220
+ console.log(chalk.blue('\nStarting the project...'));
221
+ try {
222
+ const goProcess = spawn('go', ['run', '_cmd/main.go'], {
223
+ cwd: projectDir,
224
+ stdio: ['inherit', 'pipe', 'pipe'] // 继承 stdin 和 stdout,pipe stderr
225
+ });
226
+
227
+ goProcess.on('error', (err) => {
228
+ console.error(chalk.red('Error starting project:'), chalk.redBright(err.message));
229
+ });
230
+
231
+ goProcess.on('close', (code) => {
232
+ if (code !== 0) {
233
+ console.error(chalk.red(`Project process exited with code ${code}`));
234
+ }
235
+ });
236
+
237
+ // 检查 goProcess.stdout 是否存在
238
+ if (goProcess.stdout) {
239
+ goProcess.stdout.on('data', (data) => { // 监听 stdout
240
+ const output = data.toString();
241
+ process.stdout.write(output); // 将输出写入控制台
242
+ if (output.includes('System startup successful')) {
243
+ console.log(chalk.green(`\nVisit ${chalk.bold('http://localhost:9527')} to view the project`));
244
+ }
245
+ });
246
+ } else {
247
+ console.error(chalk.red('stdout is not available.'));
248
+ }
249
+
250
+ // 检查 goProcess.stderr 是否存在
251
+ // if (goProcess.stderr) {
252
+ // goProcess.stderr.on('data', (data) => { // 监听 stderr
253
+ // const errorOutput = data.toString();
254
+ // if (errorOutput.includes('System startup successful')) {
255
+ // console.log(chalk.green(`\nVisit ${chalk.bold('http://localhost:9527')} to view the project`));
256
+ // } else {
257
+ // console.error(chalk.red(`Error: ${errorOutput}`));
258
+ // }
259
+ // });
260
+ // } else {
261
+ // console.error(chalk.red('stderr is not available.'));
262
+ // }
263
+
264
+ } catch (error) {
265
+ console.error(chalk.red('Error starting project:'), chalk.redBright(error.message));
266
+ }
267
+ } else {
268
+ console.log(chalk.blue('\nProject initialization completed without starting the project.'));
269
+ }
270
+
189
271
  } catch (error) {
190
- console.error(chalk.red('初始化项目时出错:'), chalk.redBright(error.message));
272
+ console.error(chalk.red('Error during project initialization:'), chalk.redBright(error.message));
191
273
  }
192
274
  };
193
275
 
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "gorig-cli",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
4
4
  "type": "module",
5
- "description": "gorig构建工具",
5
+ "description": "gorig build tool",
6
6
  "main": "bin/cli.js",
7
7
  "bin": {
8
8
  "gorig-cli": "./bin/cli.js"
@@ -21,6 +21,9 @@
21
21
  "chalk": "^5.3.0",
22
22
  "commander": "^12.1.0",
23
23
  "ejs": "^3.1.10",
24
- "fs-extra": "^11.2.0"
24
+ "fs-extra": "^11.2.0",
25
+ "http-server": "^14.1.1",
26
+ "js-yaml": "^4.1.0",
27
+ "semver": "^7.6.3"
25
28
  }
26
29
  }
@@ -32,12 +32,12 @@ func List<%= ModuleName %>(ctx *gin.Context) {
32
32
 
33
33
  func Save<%= ModuleName %>(ctx *gin.Context) {
34
34
  defer apix.HandlePanic(ctx)
35
- <%= ModuleName %>Req := &req.<%= ModuleName %>Req{}
36
- e := apix.BindParams(ctx, <%= ModuleName %>Req)
35
+ <%= moduleName %>Req := &req.<%= ModuleName %>Req{}
36
+ e := apix.BindParams(ctx, <%= moduleName %>Req)
37
37
  if e != nil {
38
38
  return
39
39
  }
40
- err := gService.Save<%= ModuleName %>(ctx, <%= ModuleName %>Req)
40
+ err := gService.Save<%= ModuleName %>(ctx, <%= moduleName %>Req)
41
41
  apix.HandleData(ctx, consts.CurdUpdateFailCode, nil, err)
42
42
  }
43
43
 
@@ -1,6 +1,7 @@
1
1
  package domain
2
2
 
3
3
  import (
4
+ "github.com/gin-gonic/gin"
4
5
  "github.com/jom-io/gorig/httpx"
5
6
  "github.com/jom-io/gorig/serv"
6
7
  configure "github.com/jom-io/gorig/utils/cofigure"
@@ -8,6 +9,11 @@ import (
8
9
  )
9
10
 
10
11
  func init() {
12
+ httpx.RegisterRouter(func(groupRouter *gin.RouterGroup) {
13
+ groupRouter.GET("/", func(ctx *gin.Context) {
14
+ httpx.Success(ctx, "hello world, this is <%= projectNameUpper %> project generated by gorig-cli")
15
+ })
16
+ })
11
17
  err := serv.RegisterService(
12
18
  serv.Service{
13
19
  Code: "<%= projectNameUpper %>_HTTP",
@@ -1,7 +1,7 @@
1
1
  package model
2
2
 
3
3
  type <%= moduleName.charAt(0).toUpperCase() + moduleName.slice(1) %>D struct {
4
- UserID int64 `gorm:"column:user_id;type:bigint(20);comment:user_id" json:"userID"`
5
- FiledStr string `gorm:"column:fieldStr;type:varchar(255);comment:fieldStr" json:"fieldStr"`
6
- FieldInt int64 `gorm:"column:fieldInt;type:bigint(20);comment:fieldInt" json:"fieldInt"`
4
+ UserID int64 `gorm:"column:user_id;type:bigint(20);comment:user_id" json:"userID" form:"userID"`
5
+ FiledStr string `gorm:"column:fieldStr;type:varchar(255);comment:fieldStr" json:"fieldStr" form:"fieldStr"`
6
+ FieldInt int64 `gorm:"column:fieldInt;type:bigint(20);comment:fieldInt" json:"fieldInt" form:"fieldInt"`
7
7
  }
@@ -0,0 +1,102 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>API Documentation</title>
5
+ <!-- Include ReDoc CDN -->
6
+ <script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
7
+ <style>
8
+ body {
9
+ margin: 0;
10
+ padding: 0;
11
+ font-family: Arial, sans-serif;
12
+ background-color: #f9f9f9;
13
+ color: #333;
14
+ }
15
+ #header {
16
+ padding: 15px;
17
+ background-color: #007bff;
18
+ position: fixed;
19
+ top: 0;
20
+ width: 100%;
21
+ z-index: 1000;
22
+ box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
23
+ }
24
+ #header label {
25
+ color: white;
26
+ font-weight: bold;
27
+ }
28
+ #spec-selector {
29
+ padding: 8px;
30
+ font-size: 16px;
31
+ border: none;
32
+ border-radius: 4px;
33
+ margin-left: 10px;
34
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
35
+ }
36
+ #view-source, #go-home {
37
+ margin-left: 10px;
38
+ cursor: pointer;
39
+ color: white;
40
+ text-decoration: underline;
41
+ font-weight: bold;
42
+ }
43
+ #redoc-container {
44
+ height: calc(100vh - 70px);
45
+ margin-top: 70px;
46
+ padding: 20px;
47
+ border-radius: 8px;
48
+ box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
49
+ }
50
+ </style>
51
+ </head>
52
+ <body>
53
+ <div id="header">
54
+ <label for="spec-selector">Select API Documentation: </label>
55
+ <select id="spec-selector">
56
+ <option value="">-- Select API --</option>
57
+ {{API_OPTIONS}}
58
+ </select>
59
+ <span id="view-source">View Source Data</span>
60
+ <span id="go-home" class="view-source">All List</span>
61
+ </div>
62
+ <div id="redoc-container">
63
+ <!-- ReDoc will render here -->
64
+ </div>
65
+ <script>
66
+ const selector = document.getElementById('spec-selector');
67
+ const container = document.getElementById('redoc-container');
68
+ const viewSource = document.getElementById('view-source');
69
+ const goHome = document.getElementById('go-home');
70
+
71
+ // Default select the first document
72
+ selector.selectedIndex = 1;
73
+ const defaultSpecUrl = selector.value;
74
+ if (defaultSpecUrl) {
75
+ // Render the default API documentation using ReDoc
76
+ Redoc.init(defaultSpecUrl, { scrollYOffset: 50 }, container);
77
+ }
78
+
79
+ selector.addEventListener('change', function() {
80
+ const specUrl = this.value;
81
+ if (specUrl) {
82
+ // Clear existing ReDoc rendering
83
+ container.innerHTML = '';
84
+ // Render the new API documentation using ReDoc
85
+ Redoc.init(specUrl, { scrollYOffset: 50 }, container);
86
+ }
87
+ });
88
+
89
+ viewSource.addEventListener('click', function() {
90
+ const specUrl = selector.value;
91
+ if (specUrl) {
92
+ // Redirect to the corresponding API source data
93
+ window.location.href = specUrl.replace('.json', '.json'); // Assuming source data is in JSON format
94
+ }
95
+ });
96
+
97
+ goHome.addEventListener('click', function() {
98
+ window.location.href = '/';
99
+ });
100
+ </script>
101
+ </body>
102
+ </html>
@@ -7,12 +7,12 @@ import (
7
7
 
8
8
  func init() {
9
9
  httpx.RegisterRouter(func(groupRouter *gin.RouterGroup) {
10
- <%= ModuleName %> := groupRouter.Group("<%= moduleName %>")
11
- //<%= ModuleName %>.Use(mid.SignMP())
12
- <%= ModuleName %>.GET("page", Page<%= ModuleName %>)
13
- <%= ModuleName %>.GET("list", List<%= ModuleName %>)
14
- <%= ModuleName %>.POST("save", Save<%= ModuleName %>)
15
- <%= ModuleName %>.GET("info", Get<%= ModuleName %>)
16
- <%= ModuleName %>.DELETE("delete", Delete<%= ModuleName %>)
10
+ <%= moduleName %> := groupRouter.Group("<%= moduleName %>")
11
+ //<%= moduleName %>.Use(mid.SignMP())
12
+ <%= moduleName %>.GET("page", Page<%= ModuleName %>)
13
+ <%= moduleName %>.GET("list", List<%= ModuleName %>)
14
+ <%= moduleName %>.POST("save", Save<%= ModuleName %>)
15
+ <%= moduleName %>.GET("info", Get<%= ModuleName %>)
16
+ <%= moduleName %>.DELETE("delete", Delete<%= ModuleName %>)
17
17
  })
18
18
  }