vars.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. package dartgen
  2. import "text/template"
  3. var funcMap = template.FuncMap{
  4. "getBaseName": getBaseName,
  5. "getPropertyFromMember": getPropertyFromMember,
  6. "isDirectType": isDirectType,
  7. "isNumberType": isNumberType,
  8. "isClassListType": isClassListType,
  9. "getCoreType": getCoreType,
  10. "lowCamelCase": lowCamelCase,
  11. "normalizeHandlerName": normalizeHandlerName,
  12. "hasUrlPathParams": hasUrlPathParams,
  13. "extractPositionalParamsFromPath": extractPositionalParamsFromPath,
  14. "makeDartRequestUrlPath": makeDartRequestUrlPath,
  15. }
  16. const (
  17. apiFileContent = `import 'dart:io';
  18. import 'dart:convert';
  19. import '../vars/kv.dart';
  20. import '../vars/vars.dart';
  21. /// 发送POST请求.
  22. ///
  23. /// data:为你要post的结构体,我们会帮你转换成json字符串;
  24. /// ok函数:请求成功的时候调用,fail函数:请求失败的时候会调用,eventually函数:无论成功失败都会调用
  25. Future apiPost(String path, dynamic data,
  26. {Map<String, String> header,
  27. Function(Map<String, dynamic>) ok,
  28. Function(String) fail,
  29. Function eventually}) async {
  30. await _apiRequest('POST', path, data,
  31. header: header, ok: ok, fail: fail, eventually: eventually);
  32. }
  33. /// 发送GET请求.
  34. ///
  35. /// ok函数:请求成功的时候调用,fail函数:请求失败的时候会调用,eventually函数:无论成功失败都会调用
  36. Future apiGet(String path,
  37. {Map<String, String> header,
  38. Function(Map<String, dynamic>) ok,
  39. Function(String) fail,
  40. Function eventually}) async {
  41. await _apiRequest('GET', path, null,
  42. header: header, ok: ok, fail: fail, eventually: eventually);
  43. }
  44. Future _apiRequest(String method, String path, dynamic data,
  45. {Map<String, String> header,
  46. Function(Map<String, dynamic>) ok,
  47. Function(String) fail,
  48. Function eventually}) async {
  49. var tokens = await getTokens();
  50. try {
  51. var client = HttpClient();
  52. HttpClientRequest r;
  53. if (method == 'POST') {
  54. r = await client.postUrl(Uri.parse(serverHost + path));
  55. } else {
  56. r = await client.getUrl(Uri.parse(serverHost + path));
  57. }
  58. var strData = '';
  59. if (data != null) {
  60. strData = jsonEncode(data);
  61. }
  62. if (method == 'POST') {
  63. r.headers.set('Content-Type', 'application/json; charset=utf-8');
  64. r.headers.set('Content-Length', utf8.encode(strData).length);
  65. }
  66. if (tokens != null) {
  67. r.headers.set('Authorization', tokens.accessToken);
  68. }
  69. if (header != null) {
  70. header.forEach((k, v) {
  71. r.headers.set(k, v);
  72. });
  73. }
  74. r.write(strData);
  75. var rp = await r.close();
  76. var body = await rp.transform(utf8.decoder).join();
  77. print('${rp.statusCode} - $path');
  78. print('-- request --');
  79. print(strData);
  80. print('-- response --');
  81. print('$body \n');
  82. if (rp.statusCode == 404) {
  83. if (fail != null) fail('404 not found');
  84. } else {
  85. Map<String, dynamic> base = jsonDecode(body);
  86. if (rp.statusCode == 200) {
  87. if (base['code'] != 0) {
  88. if (fail != null) fail(base['desc']);
  89. } else {
  90. if (ok != null) ok(base['data']);
  91. }
  92. } else if (base['code'] != 0) {
  93. if (fail != null) fail(base['desc']);
  94. }
  95. }
  96. } catch (e) {
  97. if (fail != null) fail(e.toString());
  98. }
  99. if (eventually != null) eventually();
  100. }
  101. `
  102. apiFileContentV2 = `import 'dart:io';
  103. import 'dart:convert';
  104. import '../vars/kv.dart';
  105. import '../vars/vars.dart';
  106. /// send request with post method
  107. ///
  108. /// data: any request class that will be converted to json automatically
  109. /// ok: is called when request succeeds
  110. /// fail: is called when request fails
  111. /// eventually: is always called until the nearby functions returns
  112. Future apiPost(String path, dynamic data,
  113. {Map<String, String>? header,
  114. Function(Map<String, dynamic>)? ok,
  115. Function(String)? fail,
  116. Function? eventually}) async {
  117. await _apiRequest('POST', path, data,
  118. header: header, ok: ok, fail: fail, eventually: eventually);
  119. }
  120. /// send request with get method
  121. ///
  122. /// ok: is called when request succeeds
  123. /// fail: is called when request fails
  124. /// eventually: is always called until the nearby functions returns
  125. Future apiGet(String path,
  126. {Map<String, String>? header,
  127. Function(Map<String, dynamic>)? ok,
  128. Function(String)? fail,
  129. Function? eventually}) async {
  130. await _apiRequest('GET', path, null,
  131. header: header, ok: ok, fail: fail, eventually: eventually);
  132. }
  133. Future _apiRequest(String method, String path, dynamic data,
  134. {Map<String, String>? header,
  135. Function(Map<String, dynamic>)? ok,
  136. Function(String)? fail,
  137. Function? eventually}) async {
  138. var tokens = await getTokens();
  139. try {
  140. var client = HttpClient();
  141. HttpClientRequest r;
  142. if (method == 'POST') {
  143. r = await client.postUrl(Uri.parse(serverHost + path));
  144. } else {
  145. r = await client.getUrl(Uri.parse(serverHost + path));
  146. }
  147. var strData = '';
  148. if (data != null) {
  149. strData = jsonEncode(data);
  150. }
  151. if (method == 'POST') {
  152. r.headers.set('Content-Type', 'application/json; charset=utf-8');
  153. r.headers.set('Content-Length', utf8.encode(strData).length);
  154. }
  155. if (tokens != null) {
  156. r.headers.set('Authorization', tokens.accessToken);
  157. }
  158. if (header != null) {
  159. header.forEach((k, v) {
  160. r.headers.set(k, v);
  161. });
  162. }
  163. r.write(strData);
  164. var rp = await r.close();
  165. var body = await rp.transform(utf8.decoder).join();
  166. print('${rp.statusCode} - $path');
  167. print('-- request --');
  168. print(strData);
  169. print('-- response --');
  170. print('$body \n');
  171. if (rp.statusCode == 404) {
  172. if (fail != null) fail('404 not found');
  173. } else {
  174. Map<String, dynamic> base = jsonDecode(body);
  175. if (rp.statusCode == 200) {
  176. if (base['code'] != 0) {
  177. if (fail != null) fail(base['desc']);
  178. } else {
  179. if (ok != null) ok(base['data']);
  180. }
  181. } else if (base['code'] != 0) {
  182. if (fail != null) fail(base['desc']);
  183. }
  184. }
  185. } catch (e) {
  186. if (fail != null) fail(e.toString());
  187. }
  188. if (eventually != null) eventually();
  189. }`
  190. tokensFileContent = `class Tokens {
  191. /// 用于访问的token, 每次请求都必须带在Header里面
  192. final String accessToken;
  193. final int accessExpire;
  194. /// 用于刷新token
  195. final String refreshToken;
  196. final int refreshExpire;
  197. final int refreshAfter;
  198. Tokens(
  199. {this.accessToken,
  200. this.accessExpire,
  201. this.refreshToken,
  202. this.refreshExpire,
  203. this.refreshAfter});
  204. factory Tokens.fromJson(Map<String, dynamic> m) {
  205. return Tokens(
  206. accessToken: m['access_token'],
  207. accessExpire: m['access_expire'],
  208. refreshToken: m['refresh_token'],
  209. refreshExpire: m['refresh_expire'],
  210. refreshAfter: m['refresh_after']);
  211. }
  212. Map<String, dynamic> toJson() {
  213. return {
  214. 'access_token': accessToken,
  215. 'access_expire': accessExpire,
  216. 'refresh_token': refreshToken,
  217. 'refresh_expire': refreshExpire,
  218. 'refresh_after': refreshAfter,
  219. };
  220. }
  221. }
  222. `
  223. tokensFileContentV2 = `class Tokens {
  224. /// 用于访问的token, 每次请求都必须带在Header里面
  225. final String accessToken;
  226. final int accessExpire;
  227. /// 用于刷新token
  228. final String refreshToken;
  229. final int refreshExpire;
  230. final int refreshAfter;
  231. Tokens({
  232. required this.accessToken,
  233. required this.accessExpire,
  234. required this.refreshToken,
  235. required this.refreshExpire,
  236. required this.refreshAfter
  237. });
  238. factory Tokens.fromJson(Map<String, dynamic> m) {
  239. return Tokens(
  240. accessToken: m['access_token'],
  241. accessExpire: m['access_expire'],
  242. refreshToken: m['refresh_token'],
  243. refreshExpire: m['refresh_expire'],
  244. refreshAfter: m['refresh_after']);
  245. }
  246. Map<String, dynamic> toJson() {
  247. return {
  248. 'access_token': accessToken,
  249. 'access_expire': accessExpire,
  250. 'refresh_token': refreshToken,
  251. 'refresh_expire': refreshExpire,
  252. 'refresh_after': refreshAfter,
  253. };
  254. }
  255. }
  256. `
  257. )