Skip to content

Commit 3117cb7

Browse files
committed
✨ Add feature that create directory from url.
1 parent 67534b1 commit 3117cb7

File tree

2 files changed

+45
-17
lines changed

2 files changed

+45
-17
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@
22
vendor
33
node_modules
44
.gitignore
5-
*.go
5+
*.go
6+
tmp

bin/api-to-go.js

Lines changed: 43 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,52 @@
11
#! /usr/bin/env node
22
const fetch = require('node-fetch');
33
const fs = require('fs');
4-
5-
64
const jsonToGo = require('../vendor/json-to-go/json-to-go.js');
75

8-
if (process.argv.length !== 3) {
9-
console.log("parameter is wrong.")
10-
return
6+
function run() {
7+
if (process.argv.length !== 3) {
8+
console.log("parameter is wrong.")
9+
return
10+
}
11+
12+
const apiUrl = process.argv[2].replace(/\/$/, '')
13+
fetch(apiUrl)
14+
.then(res => res.json())
15+
.then(json => {
16+
let res = jsonToGo(JSON.stringify(json), 'AutoGenerated');
17+
const url = new URL(apiUrl);
18+
const path = _parsePath(`${url.hostname}${url.pathname}`)
19+
const content = _buildContent(res.go, path.pkg)
20+
fs.mkdirSync(path.dir, {recursive: true})
21+
fs.writeFile(path.filePath, content, (err) => {
22+
if (err) throw err;
23+
console.log(`generated: ${path.filePath}`);
24+
});
25+
}
26+
);
1127
}
1228

13-
fetch(process.argv[2])
14-
.then(res =>res.json())
15-
.then(json => {
16-
let res = jsonToGo(JSON.stringify(json), 'AutoGenerated');
17-
fs.writeFile("hoge.go", res.go, (err) => {
18-
if (err) throw err;
19-
console.log('generated.');
20-
});
21-
return console.log( res.go );
22-
}
23-
);
29+
function _parsePath(path) {
30+
const pathArr = path.split("/")
31+
const file = pathArr[pathArr.length - 1]+".go"
32+
const pkg = pathArr[pathArr.length - 2]
33+
pathArr.pop()
34+
const dir = pathArr.join("/")
35+
return {
36+
file,
37+
pkg,
38+
dir,
39+
filePath:`${dir}/${file}`
40+
}
41+
}
2442

43+
function _buildContent(struct, packageName) {
44+
let content = `package ${packageName}\n\n`
45+
if (struct.indexOf('time.')) {
46+
content = `${content}import "time"\n\n`
47+
}
48+
content = `${content}${struct}`
49+
return content
50+
}
2551

52+
run()

0 commit comments

Comments
 (0)